Comments
yourfanat wrote: I am using another tool for Oracle developers - dbForge Studio for Oracle. This IDE has lots of usefull features, among them: oracle designer, code competion and formatter, query builder, debugger, profiler, erxport/import, reports and many others. The latest version supports Oracle 12C. More information here.

2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Today's Top SOA Links


Android Encrypted Databases
Encryption as a security topic is perhaps the weakest link in that community

The Android development community, as might be expected, is a pretty vibrant community with a lot of great contributors helping people out. Since Android is largely based upon Java, there is a lot of skills reusability between the Java client dev community and the Android Dev community.

As I mentioned before, encryption as a security topic is perhaps the weakest link in that community at this time. Perhaps, but since that phone/tablet could end up in someone else’s hands much more easily than your desktop or even laptop, it is something that needs a lot more attention from business developers.

When I set out to write my first complex app for Android, I determined to report back to you from time-to-time about what needed better explanation or intuitive solutions. Much has been done in the realm of “making it easier”, except for security topics, which still rank pretty low on the priority list. So using encrypted SQLite databases is the topic of this post. If you think it’s taking an inordinate amount of time for me to complete this app, consider that I’m doing it outside of work. This blog was written during work hours, but all of the rest of the work is squeezed into two hours a night on the nights I’m able to dedicate time. Which is far from every night.

For those of you who are not developers, here’s the synopsis so you don’t have to paw through code with us: It’s not well documented, but it’s possible, with some caveats. I wouldn’t use this method for large databases that need indexes over them, but for securing critical data it works just fine. At the end I propose a far better solution that is outside the purview of app developers and would pretty much have to be implemented by the SQLite team.

Okay, only developers left? Good.

In my research, there were very few useful suggestions for designing secure databases. They fall into three categories:

  1. Use the NDK to write a variant of SQLite that encrypts at the file level. For most Android developers this isn’t an option, and I’m guessing the SQLite team wouldn’t be thrilled about you mucking about with their database – it serves a lot more apps than yours.
  2. Encrypt the entire SD card through the OS and then store the DB there. This one works, but slows the function of the entire tablet/phone down because you’ve now (again) mucked with resources used by other apps. I will caveat that if you can get your users to do this, it is the currently available solution that allows indices over encrypted data.
  3. Use one of several early-beta DB encryption tools. I was uncomfortable doing this with production systems. You may feel differently, particularly after some of them have matured.

I didn’t like any of these options, so I did what we’ve had to do in the past when a piece of data was so dangerous in the wrong hands it needed encrypting. I wrote an interface to the DB that encrypts and decrypts as data is inserted and removed. In Android the only oddity you won’t find in other Java environments – or you can more easily get around in other Java environments – is filling list boxes from the database. For that I had to write a custom provider that took care of on-the-fly decryption and insertion to the list.

My solution follows. There are a large varieties of ways that you could solve this problem in Java, this one is where I went because

  1. I don’t have a lot of rows for any given table.
  2. The data does not need to be indexed.

If either of these items is untrue for your implementation, you’ll either have to modify this implementation or find an alternate solution.

So first the encryption handler. Note that in this sample, I chose to encode encrypted arrays of bytes as Strings. I do not guarantee this will work for your scenario, and suggest you keep them as arrays of bytes until after decryption. Also note that this sample was built from a working one by obfuscating what the actual source did and making some modifications for simplification of example. It was not tested after the final round of simplification, but should be correct throughout.

package com.company.monitor;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class DBEncryptor {
private static byte[] key;
private static String cypherType = cypherType;

public DBEncryptor(String localPass) {

// save the encoded key for future use
// - note that this keeps it in memory, and is not strictly safe
key = encode(localPass.getBytes()).getBytes();
String keyCopy = new String(key);
while(keyCopy.length() < 16)
keyCopy = keyCopy + keyCopy;

byte keyA[] = keyCopy.getBytes();
if(keyA.length > 16)
key = System.arraycopy(keyA, 0, key, 0, 16);
}

public String encode(byte [] s) {

return Base64.encodeToString(s, Base64.URL_SAFE);
}

public byte[] decode(byte[] s) {
return Base64.decode(s, Base64.URL_SAFE);
}


public byte[] getKey() {
// return a copy of the key.
return key.clone();
}

public String encrypt(String toEncrypt) throws Exception {

//Create your Secret Key Spec, which defines the key transformations
SecretKeySpec skeySpec = new SecretKeySpec(key, cypherType);

//Get the cipher
Cipher cipher = Cipher.getInstance(cypherType);

//Initialize the cipher
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

//Encrypt the string into bytes
byte[ ] encryptedBytes = cipher.doFinal(toEncrypt.getBytes());

//Convert the encrypted bytes back into a string
String encrypted = encode(encryptedBytes);

return encrypted;
}

public String decrypt(String encryptedText) throws Exception {

// Get the secret key spec
SecretKeySpec skeySpec = new SecretKeySpec(key, cypherType);

// create an AES Cipher
Cipher cipher = Cipher.getInstance(cypherType);

// Initialize it for decryption
cipher.init(Cipher.DECRYPT_MODE, skeySpec);

// Get the decoded bytes
byte[] toDecrypt = decode(encryptedText.getBytes());

// And finally, do the decryption.
byte[] clearText = cipher.doFinal(toDecrypt);

return new String(clearText);
}
}

So what we are essentially doing is base-64 encoding the string to be encrypted, and then encrypting the base-64 value using standard Java crypto classes. We simply reverse the process to decrypt a string. Note that this class is also useful if you’re storing values in the Properties file and wish them to be encrypted, since it simply operates on strings.

The value you pass in to create the key needs to be something that is unique to the user or tablet. When it comes down to it, this is your password, and should be treated as such (hence why I changed the parameter name to localPass).

For seasoned Java developers, there’s nothing new on Android at this juncture. We’re just encrypting and decrypting data.

Next it does leave the realm of other Java platforms because the database is utilizing SQLite, which is not generally what you’re writing Java to outside of Android. Bear with me while we go over this class.

The SQLite database class follows. Of course this would need heavy modification to work with your database, but the skeleton is here. Note that not all fields have to be encrypted. You can mix and match, no problems at all. That is one of the things I like about this solution, if I need an index for any reason, I can create an unencrypted field of a type other than blob and index on it.

package com.company.monitor;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBManagernames extends SQLiteOpenHelper {
public static final String TABLE_NAME = "Map";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_LOCAL = "Local";
public static final String COLUMN_WORLD = "World";


private static int indexId = 0;
private static int indexLocal = 1;
private static int indexWorld = 2;

private static final String DATABASE_NAME = "Mappings.db";
private static final int DATABASE_VERSION = 1;

// SQL statement to create the DB
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_LOCAL
+ " BLOB not null, " + COLUMN_WORLD +" BLOB not null);";

public DBManagernames(Context context, CursorFactory factory) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Yeah, this isn't implemented in production yet either. It's low on the list, but definitely "on the list"

}

// Assumes DBEncryptor was used to convert the fields of name before calling insert
public void insertToDB(DBNameMap name) {
ContentValues cv = new ContentValues();

cv.put(COLUMN_LOCAL, name.getName().getBytes());
cv.put(COLUMN_WORLD, name.getOtherName().getBytes());

getWritableDatabase().insert(TABLE_NAME, null, cv);
}

// returns the encrypted values to be manipulated with the decryptor.   
public DBNameMap readFromDB(Integer index) {

SQLiteDatabase db = getReadableDatabase();
DBNameMap hnm = new DBNameMap();
Cursor cur = null;
try {
cur = db.query(TABLE_NAME, null, "_id='"+index.toString() +"'", null, null, null, COLUMN_ID);
// cursors connsistently return before the first element. Move to the first.
cur.moveToFirst();
byte[] name = cur.getBlob(indexLocal);
byte [] othername = cur.getBlob(indexWorld);

hnm = new DBNameMap(new String(name), new String(othername), false);
} catch(Exception e) {
System.out.println(e.toString());
// Do nothing - we want to return the empty host name map.
}
return hnm;

}

// NOTE: This routine assumes "String name" is the encrypted version of the string.   
public DBNameMap getFromDBByName(String name) {
SQLiteDatabase db = getReadableDatabase();
Cursor cur = null;
String check = null;
try {
// Note - the production version of this routine actually uses the "where" field to get the correct
// element instead of looping the table. This is here for your debugging use.
cur = db.query(TABLE_NAME, null, null, null, null, null, null);
for(cur.moveToFirst();(!cur.isLast());cur.moveToNext()) {
check = new String(cur.getBlob(indexLocal));
if(check.equals(name))
return new DBNameMap(check, new String(cur.getBlob(indexWorld)), false);

}
if(cur.isLast())
return new DBNameMap();

return new DBNameMap(cur.getString(indexLocal), cur.getString(indexWorld), false);
} catch(Exception e) {
System.out.println(e.toString());
return new DBNameMap();
}

}


// used by our list adapter - coming next in the blog.
public Cursor getCursor() {
try {

return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
} catch(Exception e) {
System.out.println(e.toString());
return null;
}
}

// This is used in our list adapter for mapping to fields.
public String[] listColumns() {
return new String[] {COLUMN_LOCAL};
}


}

I am not including the DBNameMap class, as it is a simple container that has two string fields and maps one name to another.

Finally, we have the List Provider. Android requires that you populate lists with a provider, and has several base ones to work with. The problem with the SimpleCursorAdapter is that it assumes an unencrypted database, and we just invested a ton of time making the DB encrypted. There are several possible solutions to this problem, and I present the one I chose here. I extended ResourceCursorAdapter and implemented decryption right in the routines, leaving not much to do in the list population section of my activity but to assign the correct adapter.

package com.company.monitor;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

public class EncryptedNameAdapter extends ResourceCursorAdapter {

private String pw;

public EncryptedHostNameAdapter(Context context, int layout, Cursor c,
boolean autoRequery) {
super(context, layout, c, autoRequery);
}

public EncryptedHostNameAdapter(Context context, int layout, Cursor c,
int flags) {
super(context, layout, c, flags);
}

// This class must know what the encryption key is for the DB before filling the list,
// so this call must be made before the list is populated. The first call after the constructor works.
public void setPW(String pww) {
pw = pww;
}


@Override
public View newView(Context context, Cursor cur, ViewGroup parent) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.my_list_entry, parent, false);
}

@Override
public void bindView(View arg0, Context arg1, Cursor arg2) {
// Get an encryptor/decryptor for our data.
DBEncryptor enc = new DBEncryptor(pw);

// Get the TextView we're placing the data into.
TextView tvLocal = (TextView)arg0.findViewById(R.id.list_entry_name);
// Get the bytes from the cursor
byte[] bLocal = arg2.getBlob(arg2.getColumnIndex(DBManagerNames.COLUMN_LOCAL ));
// Convert bytes to a string
String local = new String(bSite);

try {
// decrypt the string
local = enc.decrypt(local);
} catch(Exception e) {
System.out.println(e.toString());

// local holds the encrypted version at this point, fix it.

// We’ll return an empty string for simplicity
local = new String();  
}
tvSite.setText(local);
}

}

The EncryptedNameAdapter can be set as the source for any listbox just like most examples set an ArrayAdapter as the source. Of course, it helps if you’ve put some data in the database first Winking smile.

That’s it for this time. There’s a lot more going on with this project, and I’ll present my solution for SSL certificate verification some time in the next couple of weeks, but for now if you need to encrypt some fields of a database, this is one way to get it done. Ping me on any of the social media outlets or here in the comments if you know of a more elegant/less resource intensive solution, always up for learning more.

And please, if you find an error, it was likely introduced in the transition to something I was willing to throw out here publicly, but let me know so others don’t have problems. I’ve done my best not to introduce any, but always get a bit paranoid if I changed it after my last debug session – and I did to simplify and sanitize.

Read the original blog entry...

About Don MacVittie
Don MacVittie is Founder of Ingrained Technology, LLC, specializing in Development, Devops, and Cloud Strategy. Previously, he was a Technical Marketing Manager at F5 Networks. As an industry veteran, MacVittie has extensive programming experience along with project management, IT management, and systems/network administration expertise.

Prior to joining F5, MacVittie was a Senior Technology Editor at Network Computing, where he conducted product research and evaluated storage and server systems, as well as development and outsourcing solutions. He has authored numerous articles on a variety of topics aimed at IT professionals. MacVittie holds a B.S. in Computer Science from Northern Michigan University, and an M.S. in Computer Science from Nova Southeastern University.

Web 2.0 Latest News
Despite the data privacy protections supposedly conferred by regulations like HIPAA and HITECH, consumers’ confidential health and personal information is still not safe enough. That’s the lesson to be learned from Franklin, TN-based Community Health Systems’ (CHS) August 18 regulatory...
Putting on a rock show is like piloting the Millenium Falcon – it’s simultaneously the fastest ship in the galaxy while being a “piece of junk.” The stage lights are so hot you start to sweat immediately, hoping those Jager-bombs are escaping through your pores and delaying the impend...
The IT infrastructure of modern businesses require a number of seemingly never-ending cycles to track assets. As these assets go through different stages of usefulness or functionality, IT teams must constantly manage the process, which takes them away from other more important tasks a...
The Open Group and BriefingsDirect recently assembled a distinguished panel at The Open Group Boston Conference 2014 to explore the practical implications and limits of the Internet of Things. This so-called Internet of Things means more data, more cloud connectivity and management, a...
General Electric (GE) has been a household name for more than a century, thanks in large part to its role in making households easier to run. Starting with the light bulb invented by its founder, Thomas Edison, GE has been selling devices (“things”) to consumers throughout its 122-year...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021




SYS-CON Featured Whitepapers
ADS BY GOOGLE