How to store the Credentials securely in Android

Most of the applications in the Market store credentials (let it be username/password or a hash) in the application to avoid prompting the user continuously asking him for the authentication. While being a good pattern to make the application usage more fluent, it is not exempt of security risks.

Android provides different options to store data from an application. From all those, the SharedPreferences seems to be the most adequate to store credentials: it stores primitive types in an XML file, which is in principle saved in the application package folder and hidden to the user in most cases. A device that has been rooted, however, can access this folder and retrieve the SharedPreferences files, exposing the credentials if we have chosen to store them this way.

This problem also affects integrity of another applications, and allows operations such as game cheating. Srinivas proves in his blog how is possible to edit the score in Stick Cricket and submit a modified one to the server.

A rooted device always makes security harder, but we can ensure that our authentication is securely stored by combining a few techniques. Encryption is the first thing that comes in mind, but if we want to encrypt we might need to use a key, that also needs to be stored somewhere else. NDK comes here into the scene: we can store using native code the key or sequence we will use to encrypt our data. Let’s see it step by step.

First, we will write two functions to encrypt and decrypt our data. We will use AES for our purpose:

The functions are very straight-forward. Now we can use them like follows:

If we use this functionality to encrypt our data, at this point it will be encrypted but an attacker could still decompile our APK, check the key used to encrypt the data and steal our credentials. With NDK we can store this key in an .so file, making it very hard for the attacker (.so files can hardly be decompiled, and disassembling those files is far from being a comfortable option). To store and retrieve our key, we need to write the following code in our application:

And save in a file using NDK the following function:

Now we can easily retrieve our key and use it to encrypt our data.

Security is never granted and never absolute, so the solution is to always take smart design decisions and use all the available tools to prevent unauthorised usage of our applications or systems. By applying this technique you can ensure a high level of security for your application credentials!

Tags: , ,

2 Responses to How to store the Credentials securely in Android

  1. Sergey says:

    This approach called security through obsucrity, which is well known being not effective.

  2. Irwin says:

    Good post, but what about attackers load the .so library and get secret key by call you method?

Leave a Reply

Name and Email Address are required fields. Your email will not be published or shared with third parties.