Employing Secure Data Practices on the Android Mobile Platform

Despite their small size, it is important to remember that SmartPhones and Tablets are really computers.  Sure the form factors are much smaller than the trusty laptop or desktop machines, but they pack quite a bit of computing power, and fit literally in the palm of your hand.  They are also ubiquitous, and with so many people carrying them, it is crucial that Android App Developers take steps to protect sensitive data.

manthegunsA big security concern is the risk that as mobile apps request privileges – especially advertiser supported apps – data like contacts, geolocation, browsing history and more may inadvertently be shared by the user.

For the sake of the argument, think of a scenario in which the user is required to store a credit card as a payment option on a device.  An Android developer can use a variety of ways to store such information, such as in SharedPreferences, or via internal storage with Private Mode enabled.  In the example below, we’re using the SDCard location to store the credit card details.

// Code Snippets to write information to SDCard
 try {
     String cardinforamtion = “1345678901234567|11/28/2013|123”;
File outputFile = new File(context.getExternalFilesDir(null),”mysecretfile.txt”);

FileOutputStream outputStream = new FileOutputStream(outputFile);
  } catch (FileNotFoundException e) {
         Log.e(TAG,"File not found");
  } catch (IOException e) {
      Log.e(TAG,"IO Exception");

AES Encryption

With that complete, we can later find the SD Card Location on the device or an emulator with the help of Eclipse IDE, as seen in the screen grab below:

AES Encryption2

Now we can open the file in an text editor, and there we’ll find the data as it was saved by the application.  In this example, we’re not using a real credit card number but even so, we can clearly see how such information would easily found.  The bottom line?  It’s a massive risk to save that kind of data on the Android device – especially on a removable memory card.

AES Encryption3

Resolving the Problem

Before we work towards a resolution, keep in mind that some data will be considered sensitive data, like a credit card number, while other items are not nearly so important.  For example, a person’s name isn’t what we’d call sensitive information in an application.

So we’ll first look to classify all of the data in question.  We do this because securing non-sensitive data would add delays to the amount of time it would take to complete an operation.  Below is a very basic grid displaying some data types and how those items might be classified.

AES Encryption4

In the example above you can see that we have some information listed as personal, some as sensitive, and the bulk of them falling under both categories.

Personal information is the type of information that would be known to you an a limited number of people with whom you associate.  It is generally priviledged information, but of the sort that you’d be willing to share with your family and close friends.  These items could include your physical address, an email address or your phone number.

Sensitive information however, is far more valuable, and the inadvertant disclosure of it could cause great harm.  The kind of data were referring to here would include things like your passwords, PINs, social security or tax identification numbers, as well as bank account numbers.  This is the data that you would want protected at all time – be it in transit or stored on a device.

Implement Encryption on sensitive data

One of the more widely used techniques to protect sensitive data is data encryption.  By encrypting sensitive data before writing it to a device or a memory card, we can ensure that the data written will be in a format that is difficult or impossible to decipher without a password.

In this example, we’ll use the Advanced Encryption Standard (AES) developed by the National Institutes of Standards and Technologies.  The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data.  Therefore the key will need to be stored securely to prevent an attacker from gaining access and then being able to decrypt the data.

Encryption Routine

Public static byte[] generateKey(byte[] randomNumberSeed) {
        SecretKey sKey = null;
        try {
                KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom random =                            SecureRandom.getInstance("SHA1PRNG");
                sKey = keyGen.generateKey();
        } catch (NoSuchAlgorithmException e) {
                Log.e(TAG,"No such algorithm exception");
        return sKey.getEncoded();
// Final implementation with AES encrypt
try {
     String cardDetails = cardNum.getText() + "|"+ expDate.getText() + "|" + cvv.getText();
File outputFile = new File(context.getExternalFilesDir(null),"carddata.txt");
              FileOutputStream outputStream = new FileOutputStream(outputFile);
     byte[] key = generateKey("randomtext".getBytes());  // called above defined method
     outputStream.write(encrypt(key, cardDetails.getBytes())); // called above defined method

     Log.e(TAG,"Successfully written at "+ outputFile.getAbsolutePath());
} catch (FileNotFoundException e) {
     Log.e(TAG, "File not found");
} catch (IOException e) {
Log.e(TAG, "IO Exception");

Results of Encryption

After successful encryption, if we navigate to the stored data, we’ll see a string of garbled characters.  This would then be unreadable by a casual snooper as well as a deliberate hacker so long as they don’t have access to the decryption key.

AES Encryption5

Encryption of sensitive data is essential when developing secure applications for the Android platform as it is for any other platform.  We hope this gives Android Developers a sense of where to begin and what types of data need to be protected.

Please let us know what you think and what issues you’re encountering with your mobile app development projects.  Should this Android development tutorial prove helpful to you, please feel free to share across your social networks and blogs.



  1. Sam Bosshardt

    This caveat is very important: “so long as they don’t have access to the decryption key”.

    This is a good article for someone with little to no experience with encryption, however this is not a complete solution to keeping sensitive data safe from a determined attacker. Although this is better than not encrypting at all, you are left with essentially the same problem when you started. If you have no safe place to save the credit card info, then you have no safe place to save the key to the credit card info. “Private Mode” internal storage was suggested before showing the SD Card example. This is a better place to store the data / key because the operating system protects other apps from reading the app’s data. However a determined enough attacker in theory could find some way to breach the security and get at the data you have saved.

    The example given was with a symmetric algorithm – the same key that encrypts the data also decrypts the data. I would suggest using an asymmetric algorithm such as RSA. The app author generates a public and private pair of keys. The public key is included with the app. When the user enters the credit card information, the public key is used to encrypt the data and save it to the device. As soon as the user clicks to store the credit card, the credit card data is encrypted, stored, and immediately forgotten by the app. Possibly some of the credit card info can be stored in plain text (such as the last four digits of the credit card, if it is Visa/MasterCard, possibly the expiration date). That way, the user can tell which credit card he/she is using (for example, you want to support having multiple credit cards stored and present a choice to the user).

    The private key is stored on a secure, locked down server. Whenever the user wants to initiate a transaction, the encrypted credit card information is sent to the server. The server would be running a server app that connects with a payment gateway (such as After the server receives a request from the mobile app, it decrypts the card data, submits the transaction, and records an entry in a database indicating that the user has paid. Ideally, you will not store the credit card information at all on the server – that way if somehow your server were to be breached and the private key compromised, no credit card information could be downloaded from the server because it has not stored the information. Of course if the server were to be compromised somehow, an attacker could install malicious code on it and credit card transactions could be observed as they happen during the time between the server being breached and the breach being discovered/fixed.

    I would say that combining “Private Mode” internal storage, the asymmetric encryption I outlined, and a properly secured server should be enough to keep credit card data safe. After all, neither your mobile app nor your server knows the credit card data (except during a very short window of time). I highly recommend that anyone who is developing an app that deals with very sensitive information have an expert check their code & systems for bugs and weaknesses before releasing the app. Or find another way that doesn’t involve you having access to the sensitive information in the first place such as by using a trusted third party (in the case of credit cards, integration with Google Play / Google Wallet / Paypal).

    I realize this all goes beyond the scope of a simple tutorial. I thought I’d put it out there, hopefully most developers already know this but I’m sure there are newbies out there who don’t. People can be lulled into a false sense of security when they hear something is “encrypted”. Though the road may be long, this article is a good start.

    1. Unbounded Solutions

      Very good points, Sam. As you suggested, this is more of the 30,000 ft view, and not intended to explore every nook and cranny.

Leave a Comment

Your email address will not be published. Required fields are marked *