Home > Articles > Data

  • Print
  • + Share This
This chapter is from the book

Hiding the Key

One of the most fundamental decisions that you’re going to face as a mobile developer is what encryption to use to hide sensitive information and whether you’re going to leave the information on the phone or not.

In this section we’re going to look at a number of different ways that other developers have tried to solve this problem. These examples come from real-world Android apps that we’ve audited over the years. They each get progressively better at hiding an encryption key for the database itself or for fields in the database, such as the password.

Security on Android is almost always a battle between security and ease of use. App developers want to make it easy for people to use, and they don’t think it’s a good idea to make someone log into the phone multiple times.

And while many of these examples look like very naive implementations, we have the benefit of hindsight and can probably assume that the developers were not aware that someone could gain access to their code and encryption keys so easily. If you’re using some sort of symmetrical key encryption where the encrypted data, as well as the encrypted key, are on the phone, then you’re leaving yourself open to attack.

Ask Each Time

Possibly the safest way to encrypt your database is to ask for the key each time, either using a PIN code or a password. The first time the user opens the app they’re asked for the key, which is then used to encrypt the database.

If the user wants to access any data on the app, then the next time they use the app they have to remember their key and reenter it. The key is stored in the user’s head and not on your phone.

The downside of this is that the user has to log in to the phone each time they open your app. And depending on the key size it may also be open to a brute-force attack. Certainly a four-digit pin code is not very secure.

Listing 5-4 shows an example of how to use a login password to encrypt the database. The password is captured as the user is logging in on line 31; it’s then passed to initializeSQLCipher as a string on line 35 and used as the SQLCipher key when we open the database on line 45.

Listing 5-4 Using a Login password to encrypt the database

public class LoginActivity extends Activity {

     private Button loginButton;

     protected void onCreate(Bundle savedInstanceState) {


     private void initializeViews() {
         loginButton = (Button) findViewById(R.id.login_button);
     private void bindListenersToViews() {
         loginButton.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
     private void loginToApp() {
         EditText usernameField = (EditText) findViewById(R.id.username_field);
         EditText passwordField =         // line 31
(EditText) findViewById(R.id.password_field);
         EditText emailField =  (EditText) findViewById(R.id.email_field);

         InitializeSQLCipher(passwordField.getText().toString());       // line 35
    private void InitializeSQLCipher(String pwd) {
        File databaseFile = getDatabasePath("names.db");

        SQLiteDatabase database =                                       // line 45
SQLiteDatabase.openOrCreateDatabase(databaseFile, pwd, null);
         database.execSQL("create table user(id integer primary key autoincrement,
         " +
                      "first text not null, last text not null, " +
                      "username text not null,password text not null)");

         database.execSQL("insert into user(first,last,username, password) " +

Shared Preferences

The next implementation is to hide the key in the shared preferences and then load it each time the app is opened. There are two variations on this theme. A typical app will ask the user to encrypt the app the first time and save the key in the shared preferences. Listing 5-5 shows how to write and load our encryption key from a shared preferences file.

Listing 5-5 Storing passwords in the shared preferences file

private void saveLastSuccessfulCreds() {
    String username =
((EditText) findViewById(R.id.username_field)).getText().toString();
     String password =                                                    // line 3
((EditText) findViewById(R.id.password_field)).getText().toString();

     SharedPreferences.Editor editor = sharedPrefs.edit();
     editor.putString(SettingsActivity.LAST_USERNAME_KEY, username);
     editor.putString(SettingsActivity.LAST_PASSWORD_KEY, password);      // line 7

private void loadLastSuccessfulCreds() {
    String lastUsername =
sharedPrefs.getString(SettingsActivity.LAST_USERNAME_KEY, "");
    String lastPassword =                                                // line 13
sharedPrefs.getString(SettingsActivity.LAST_PASSWORD_KEY, "");

     ((EditText) findViewById(R.id.username_field)).setText(lastUsername);
     ((EditText) findViewById(R.id.password_field)).setText(lastPassword); //line 16

The adb backup command will not only recover the databases, it will also recover the shared preferences files. Figure 5-9 shows a screenshot of someone viewing a shared preferences file on the phone itself.

Figure 5-9

Figure 5-9 Viewing shared preferences files

Alternatively, the app can load an app-specific username and password when the app is first opened. Android will load data from the resources/xml folder and store it in shared preferences. Listing 5-6 shows how to load the key from the resources folder.

Listing 5-6 Loading the SQLCipher key from the resources folder

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    android:key="myKey" />


The advantage of this is that it’s very easy to use; it encrypts the database without any user input. The disadvantage is that it’s very easy for someone to find the key and decrypt the phones. For example, the apktool—available from https://code.google.com/p/android-apktool/—will convert an APK’s resources back into xml using the following command:

java –jar apktool.jar d com.riis.sqlcipher-1.apk

In the Code

We can see from the SQLCipher code example earlier in Figure 5-8 that we can’t simply hard code our key in the SQLCipher class because someone is going to find it when they decompile your APK. If we create a security scale showing level of difficulty—from 1 to 10, where 1 is your kid brother and 10 is a foreign government—then we’re close to 1 or 2 in the level of difficulty to reverse engineer an APK to decompile the code.

A couple of years ago, using a single security key for everyone’s app was common practice in Android development. More recently, developers have moved to generating the key and making it device-specific using the device’s attributes, such as device_id, android_id, and any number of phone-specific attributes such as BUILD ID’s, and Build.MODEL and Build.MANUFACTURER. This is then concatenated together and is a unique key for that phone or tablet. Listing 5-7 shows how you might do that. It takes the device’s unique Android ID and the Device ID (assuming it’s not a tablet) as well as a whole array of phone information. All of this information is concatenated together and converted into an md5 digest or hash value.

So far, so good. It protects the app from any potential targeted malware that would use a decompiled key to attack the app on lots of different phones. However, although the key isn’t the same on every device, the algorithm is the same. And it’s a small step if the code can be decompiled to figure out how to recreate the recipe for generating the key, so ultimately it’s only slightly more secure than using the same key.

Listing 5-7 Device-specific keys

android_id =
tManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
device_id = tManager.getDeviceId();

String str1 = Build.BOARD + Build.BRAND + Build.CPU_ABI + Build.DEVICE +
     Build.DISPLAY + Build.FINGERPRINT + Build.HOST + Build.ID + Build.MANUFACTURER
     Build.MODEL + Build.PRODUCT + Build.TAGS + Build.TYPE + Build.USER;
String key2 = md5(str1 + device_id + android_id);

In the NDK

If the Java code in Android can be reverse engineered so easily, then it makes sense to write it in some other language that isn’t so easily decompiled. Some developers hide their keys in C++ using the Native Developer Kit (NDK). The NDK enables developers to write code as a C++ library. This can be useful if you want to try to hide any keys in binary code. And, unlike Java code, C++ cannot be decompiled, only disassembled.

Listing 5-8 shows some simple C++ code for returning the “pass123” key to encrypt the database.

Listing 5-8 Hiding the key in the NDK

#include <string.h>
#include <jni.h>

jstring Java_com_riis_sqlndk_MainActivity_invokeNativeFunction(JNIEnv* env,
jobject javaThis) {
  return (*env)->NewStringUTF(env, "pass123");

Listing 5-9 shows the Android code to call the NDK method correctly. Line 11 does the JNI library call, the function is defined on line 14, and then we call the function that returns the key on line 21. The sqlndk.c file needs to be in a jni folder. And because it’s C++ code, we’re going to need a make file.

Listing 5-9 Calling the NDK code from Android

import java.io.File;

import net.sqlcipher.database.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

public class MainActivity extends Activity {

    static {
        System.loadLibrary("sqlndk");                           // line 11
    private native String invokeNativeFunction();               // line 14

    protected void onCreate(Bundle savedInstanceState) {

         String sqlkey = invokeNativeFunction();                 // line 21 
         new AlertDialog.Builder(this).setMessage(sqlkey).show();


   private void InitializeSQLCipher(String initKey) {
       File databaseFile = getDatabasePath("tasks.db");
       SQLiteDatabase database =
          SQLiteDatabase.openOrCreateDatabase(databaseFile, initKey, null);
       database.execSQL("create table tasks" +
                 " (id integer primary key autoincrement,title text not null)");
       database.execSQL("insert into tasks(title) values('Placeholder 1')");

Listing 5-10 shows the corresponding Android.mk file. The C++ code is compiled using the ndk-build command that comes with the Android NDK tools. ndk-build is run from a cgywin command line if you’re on Windows.

Listing 5-10 NDK makefile

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_SRC_FILES := sqlndk.c


But we’re not there yet. Even though we can no longer decompile the code, we can disassemble it. Looking at Figure 5-10 you can see where the library, opened up in a hexadecimal editor, shows the key very clearly at the end of the hexidecimal strings in the file.

Figure 5-10

Figure 5-10 Viewing the NDK password

If you’re going to use the NDK, then choose hexadecimal-like text so that it doesn’t stand out in a hex editor. We can also take the earlier approach and use some device-specific or app-specific characteristic and generate a unique app key in NDK just like we can in native Android code. Listing 5-11 shows how you can use the app ID as a unique key, which will be different every time the app is installed on a different phone. It uses a function called getlogin() to find out the login ID, which in this case is the app_id.

Listing 5-11 Using the App ID for the database key

#include <string.h>
#include <jni.h>
#include <unistd.h>
jstring Java_com_riis_sqlndk_MainActivity_invokeNativeFunction(JNIEnv* env,
jobject javaThis) {
     return (*env)->NewStringUTF(env, (char *)getlogin());

However, neither of these approaches is ultimately enough to stop someone from reading the binary. But it is a better option to consider if you have no other choice than to put the API or encryption keys on the device. Disassembled code rapidly becomes more difficult to understand as it gets further away from these simple helloworld examples.

Web Services

The safest option for any type of device is to store the key, or the algorithm for generating your key, remotely and to access it via secure web services. This has already been covered in previous chapters. The disadvantage to this is that the Android device will need to be connected to the Internet when you open the database, which might not be acceptable to the end user.

But the message should be clear by now that any keys stored on the phone are open to being hacked in ways similar to what we’ve shown in this section. We’ll go into more detail in the next chapter about what to do to protect your web server and your web server traffic from prying eyes.

  • + Share This
  • 🔖 Save To Your Account