Welcome!

Wireless Authors: Liz McMillan, Carmen Gonzalez, Pat Romanski, Elizabeth White, Esmeralda Swartz

Related Topics: Open Web, Wireless, SOA & WOA, Virtualization, Web 2.0, Cloud Expo

Open Web: 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 "
+ 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...

More Stories By 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.

@ThingsExpo Stories
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
Swiss innovators dizmo Inc. launches its ground-breaking software, which turns any digital surface into an immersive platform. The dizmo platform seamlessly connects digital and physical objects in the home and at the workplace. Dizmo breaks down traditional boundaries between device, operating systems, apps and software, transforming the way users work, play and live. It supports orchestration and collaboration in an unparalleled way enabling any data to instantaneously be accessed on any surface, anywhere and made interactive. Dizmo brings fantasies as seen in Sci-fi movies such as Iro...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, will describe an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people’s real needs and desires.
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...