Harsh Dattani Harsh Dattani - 1 year ago 95
Android Question

How to Secure Android Shared Preferences?

The common location where

are stored in Android apps is:

/data/data/<package name>/shared_prefs/<filename.xml>

User with root privileges can navigate to this location and can change its values.Need of protecting it is of much importance.

In how many ways we can encrypt whole
shared_pref's xml

We all know that we can encrypt and save data in
shared_pref's xml
file, but that's not only 100% safe, so need to encrypt whole file with a key. Need help in knowing various ways to encrypt whole
file. This is generic question, various encryption methods discussed as answers here can be helpful to all developers in securing apps.

Answer Source

You should note that Android's shared preferences are XML key-value based. You cannot change that fact (as it would break it's parser), at best you can encrypt both the key and the value, so the root user could read but wouldn't have the slightest idea what he is reading.

To do that, you could use a simple encryption like this

public static String encrypt(String input) {
    // Simple encryption, not very strong!
    return Base64.encodeToString(input.getBytes(), Base64.DEFAULT);

public static String decrypt(String input) {
    return new String(Base64.decode(input, Base64.DEFAULT));

This is how you would use this

// Write
SharedPreferences preferences = getSharedPreferences("some_prefs_name", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(encrypt("password"), encrypt("dummypass"));
editor.apply(); // Or commit if targeting old devices

// Read
SharedPreferences preferences = getSharedPreferences("some_prefs_name", MODE_PRIVATE);
String pass = preferences.getString(decrypt("password"), "default");

You should know tough, that SharedPreferences were never built to be secure, it's just a simple way to persist data.

You should be aware too that the encryption I have used is not the most secure, but it's simple.

There are several libraries that provide better encryption, like these

But they all come to the fact that the format of the file is still XML and it is key-value based. You cannot change that fact. See below.

cat /data/data/your.package.application/shared_prefs/prefs-test.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<string name="JopRH053b7Ogw17Yxmh7Og==">0AB7Y28XEvbQcnXpEZ4j9PtqzFLtm2V3KBXjTO1V704=</string>

The key is "hemmelighet" and the value is "dette er en hemmelighet".

If security is an issue beyond the fact that SharedPreferences is still key-value based and in XML format, you need to avoid it entirely.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download