Home > Articles > Data

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;

     @Override
     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);
           setContentView(R.layout.login_screen);
           initializeViews();
           bindListenersToViews();
 
     }

     private void initializeViews() {
         loginButton = (Button) findViewById(R.id.login_button);
     }
 
     private void bindListenersToViews() {
         loginButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                       loginToApp();
             }
     });
     }
 
     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) {
        SQLiteDatabase.loadLibs(this);
        File databaseFile = getDatabasePath("names.db");
        databaseFile.mkdirs();
        databaseFile.delete();

        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) " +
                      "values('Bertie','Ahern','bahern','celia123')");
      }
}

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
     editor.commit();
}

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

<EditTextPreference
    android:defaultValue="pass1234"
    android:key="myKey" />

</PreferenceScreen>

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 =
     Secure.getString(getBaseContext().getContentResolver(),Secure.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

 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

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

        InitializeSQLCipher(sqlkey); 
 
}

   private void InitializeSQLCipher(String initKey) {
       SQLiteDatabase.loadLibs(this);
       File databaseFile = getDatabasePath("tasks.db");
       databaseFile.mkdirs();
       databaseFile.delete();
       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_MODULE:= sqlndk
LOCAL_SRC_FILES := sqlndk.c
 

include $(BUILD_SHARED_LIBRARY)

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020