Mobile IoT Authors: Liz McMillan, Progress Blog, Pat Romanski, John Katrick, Derek Weeks

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
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning 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 busin...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited 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. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.