Secure SharedPreferences Android
In this article we will learn how we can encrypt our SharedPreferences in Android using Jetpack’s Security library
Definition : An implementation of SharedPreferences
that encrypts keys and values.
- First you need to add the following dependency in your build.gradle file of app module.
Check the latest version here for this library
Just sync your project and we are good to go.
- Now you can easily create the Encrypted SharedPrefernces instance :
- masterKey :
val masterKey = MasterKey.Builder(applicationContext)
.build()
It is used to generate the encryption keys that are used for encrypting keys and values.
- PrefKeyEncryptionScheme.AES256_SIV : It’s used to encrypt the Keys 🔑
- PrefValueEncryptionScheme.AES256_GCM : It’s used to encrypt the values
- Now we have sharedPreferences. Let’s add some values in it. We will use Android-KTX library to write more concise code :
- You can learn more about Android-KTX here.
- We have saved Name of String type in our Encrypted SharedPreferences.
Let’s check the content of saved sharedPreferences to make sure that value is saved as encrypted.
- In AndroidStudio you can see you're connected device’s data/ emulator’s data using Device File Explorer.
Under data/data/your_package_name , you can see the content of your app.
- Here is the content of the encrypted shared preferences file :
You might get wonder why there are 3 values stored because we only put the Name.
- EncryptedSharedPreferences stores the key-value that are used to encrypt the values in SharedPreference file.
That’s all for today. I hope you learn something new.
- Here is the sample code related to this article :