Release Management Authors: Liz McMillan, Jnan Dash, Lori MacVittie, Gilad Parann-Nissany, Carmen Gonzalez

Related Topics: Release Management , Mobile IoT, Microservices Expo, Containers Expo Blog, Agile Computing, @CloudExpo

Release Management : Blog Feed Post

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 "
+ " 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);


public void onCreate(SQLiteDatabase db) {


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.
byte[] name = cur.getBlob(indexLocal);
byte [] othername = cur.getBlob(indexWorld);

hnm = new DBNameMap(new String(name), new String(othername), false);
} catch(Exception e) {
// 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));
return new DBNameMap(check, new String(cur.getBlob(indexWorld)), false);

return new DBNameMap();

return new DBNameMap(cur.getString(indexLocal), cur.getString(indexWorld), false);
} catch(Exception e) {
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) {
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;

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);

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) {

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

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


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...

More Stories By Don MacVittie

Don MacVittie is founder of Ingrained Technology, A technical advocacy and software development consultancy. He has experience in application development, architecture, infrastructure, technical writing,DevOps, and IT management. MacVittie holds a B.S. in Computer Science from Northern Michigan University, and an M.S. in Computer Science from Nova Southeastern University.

@ThingsExpo Stories
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
WebRTC is about the data channel as much as about video and audio conferencing. However, basically all commercial WebRTC applications have been built with a focus on audio and video. The handling of “data” has been limited to text chat and file download – all other data sharing seems to end with screensharing. What is holding back a more intensive use of peer-to-peer data? In her session at @ThingsExpo, Dr Silvia Pfeiffer, WebRTC Applications Team Lead at National ICT Australia, looked at differ...
The security needs of IoT environments require a strong, proven approach to maintain security, trust and privacy in their ecosystem. Assurance and protection of device identity, secure data encryption and authentication are the key security challenges organizations are trying to address when integrating IoT devices. This holds true for IoT applications in a wide range of industries, for example, healthcare, consumer devices, and manufacturing. In his session at @ThingsExpo, Lancen LaChance, vic...
With all the incredible momentum behind the Internet of Things (IoT) industry, it is easy to forget that not a single CEO wakes up and wonders if “my IoT is broken.” What they wonder is if they are making the right decisions to do all they can to increase revenue, decrease costs, and improve customer experience – effectively the same challenges they have always had in growing their business. The exciting thing about the IoT industry is now these decisions can be better, faster, and smarter. Now ...
Fact is, enterprises have significant legacy voice infrastructure that’s costly to replace with pure IP solutions. How can we bring this analog infrastructure into our shiny new cloud applications? There are proven methods to bind both legacy voice applications and traditional PSTN audio into cloud-based applications and services at a carrier scale. Some of the most successful implementations leverage WebRTC, WebSockets, SIP and other open source technologies. In his session at @ThingsExpo, Da...
Who are you? How do you introduce yourself? Do you use a name, or do you greet a friend by the last four digits of his social security number? Assuming you don’t, why are we content to associate our identity with 10 random digits assigned by our phone company? Identity is an issue that affects everyone, but as individuals we don’t spend a lot of time thinking about it. In his session at @ThingsExpo, Ben Klang, Founder & President of Mojo Lingo, discussed the impact of technology on identity. Sho...
A critical component of any IoT project is what to do with all the data being generated. This data needs to be captured, processed, structured, and stored in a way to facilitate different kinds of queries. Traditional data warehouse and analytical systems are mature technologies that can be used to handle certain kinds of queries, but they are not always well suited to many problems, particularly when there is a need for real-time insights.
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
WebRTC has had a real tough three or four years, and so have those working with it. Only a few short years ago, the development world were excited about WebRTC and proclaiming how awesome it was. You might have played with the technology a couple of years ago, only to find the extra infrastructure requirements were painful to implement and poorly documented. This probably left a bitter taste in your mouth, especially when things went wrong.
WebRTC is bringing significant change to the communications landscape that will bridge the worlds of web and telephony, making the Internet the new standard for communications. Cloud9 took the road less traveled and used WebRTC to create a downloadable enterprise-grade communications platform that is changing the communication dynamic in the financial sector. In his session at @ThingsExpo, Leo Papadopoulos, CTO of Cloud9, discussed the importance of WebRTC and how it enables companies to focus o...
Providing secure, mobile access to sensitive data sets is a critical element in realizing the full potential of cloud computing. However, large data caches remain inaccessible to edge devices for reasons of security, size, format or limited viewing capabilities. Medical imaging, computer aided design and seismic interpretation are just a few examples of industries facing this challenge. Rather than fighting for incremental gains by pulling these datasets to edge devices, we need to embrace the i...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).
SYS-CON Events announced today that Catchpoint, a leading digital experience intelligence company, has been named “Silver Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Catchpoint Systems is a leading Digital Performance Analytics company that provides unparalleled insight into your customer-critical services to help you consistently deliver an amazing customer experience. Designed for digital business, C...
@ThingsExpo has been named the ‘Top WebRTC Influencer' by iTrend. iTrend processes millions of conversations, tweets, interactions, news articles, press releases, blog posts - and extract meaning form them and analyzes mobile and desktop software platforms used to communicate, various metadata (such as geo location), and automation tools. In overall placement, @ThingsExpo ranked as the number one ‘WebRTC Influencer' followed by @DevOpsSummit at 55th.
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal ...
"There's a growing demand from users for things to be faster. When you think about all the transactions or interactions users will have with your product and everything that is between those transactions and interactions - what drives us at Catchpoint Systems is the idea to measure that and to analyze it," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York Ci...
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
SYS-CON Events announced today that Linux Academy, the foremost online Linux and cloud training platform and community, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Linux Academy was founded on the belief that providing high-quality, in-depth training should be available at an affordable price. Industry leaders in quality training, provided services, and student certification passes, its goal is to c...