THE SECRET GUIDE
How to Migrate to Encrypted Shared Preferences
A step by step guide on how to migrate to encrypted shared preferences
The Android framework provides us with SharedPreferences, which is a great way to store a small collection of key-value data. When working with sensitive data, however, it’s important to understand that SharedPreferences stores data as plain text. We should encrypt sensitive data to prevent it from being hacked. How can we do so?
The Security library comes to the rescue!
The Security library, part of Android Jetpack, provides an implementation of the security best practices related to reading and writing data, as well as key creation and verification.
In this article, I’ll share with you how to migrate your existing Shared Preferences to EncryptedSharedPreferences. Stay tuned:)
Setup
To get started with the AndroidX Security library, add the following dependency to your module-level build.gradle
file.
dependencies {
implementation "androidx.security:security-crypto:1.0.0-rc01"
}
In order to use this library, you will need to set minSdkVersion
to 23+
android { defaultConfig {
minSdkVersion 23
}
}
However, in case your application is targeting devices below minSdkVersion 23, do not apply this change and add the following line to your AndroidManifest.xml:
<uses-sdk tools:overrideLibrary="androidx.security"/>
Coding-Time!
SharedPreferencesManager
Interface with all the SharedPreferences APIs supported.
SharedPreferencesManagerImpl
Handling the creation of the EncryptedSharedPreferences in case SDK version is ≥ 23, otherwise we will keep using the original non-encrypted SharedPreferences.
SharedPreferencesUtils
These methods in SharedPreferencesUtils class, extend the SharedPreferences class to give more abilities.
Summary
Android’s SharedPreferences
is a useful tool to store key-value data and when that data is sensitive, it’s a good idea to encrypt it. The recent AndroidX Security library is a welcome addition that provides us with a simple and easy-to-use interface to do so.
That’s all! I hope you liked this article.