Secure Android SharedPreferences


Did you know the data stored in local storage or shared preferences can be hacked? What if the data stored is very confidential - can be user details, api keys or some other important data which you cannot afford losing.

Securing app’s data has become very important as they have become easy to exploit targets. Android Jetpack provides a Security library which can help secure the data.

Here are two simple classes which will help you secure your data stored in files and shared preferences. These classes are part of the Security Library of Android Jetpack.

EncryptedFile - To secure app's local storage files.
EncryptedSharedPreferences - To secure app's shared preferences.

In this blog we are going to talk about 
EncryptedSharedPreferences and how it is different from existing SharedPreferences class.

What is SharedPreferences?
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. Check https://developer.android.com/training/data-storage/shared-preferences for details.

What is EncryptedSharedPreferences?
An implementation of SharedPreferences that encrypts keys and values. Wraps the SharedPreferences class and automatically encrypts keys and values using a two-scheme method:
  • Keys are encrypted using a deterministic encryption algorithm such that the key can be encrypted and properly looked up. It simpler terms keys are encrypted in a way that its cipher text will always have same value.
  • Values are encrypted using AES-256 GCM and are non-deterministic. It means every time values are encrypted it will provide different cipher text for higherl level of security.

Where does the system store share preferences? Check https://youtu.be/M3tGiWWZkIk video to know about where in the device share preferences are stored?

As seen in the video shared_prefs is the folder which contains all the files related to shared preferences. 

Let us check now how the content of share preferences files are updated based on what is used to create those files - SharedPreferences vs EncryptedSharedPreferences

Code using SharedPreferences





Content of XYZ.xml shared preference file we created using above code. You can see the content is easy to read and deduct.





Code using EncryptedSharedPreferences








Content of ABC.xml shared preference file we created using above code. You can see the content is encrypted and can be deducted directly.





Resources
This information is referred from https://developer.android.com/topic/security/data. For more details on how to use these in application can be referred using the same link.

Comments

Popular posts from this blog

Fragment Lifecycle

AndroidManifest

Activity Lifecycle