How to Secure Android Shared Preferences?
You need to handle Verisons under API 23
fun providesSharedPreference(): SharedPreferences {
var sharedPreferences: SharedPreferences
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sharedPreferences = EncryptedSharedPreferences.create(
application,
Constant.SHARED_PREFERENCE_NAME,
getMasterKey(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
} else {
sharedPreferences =
application.getSharedPreferences(
Constant.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE
)
}
return sharedPreferences
}
private fun getMasterKey(): MasterKey {
return MasterKey.Builder(application)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
}
UPDATED ANSWER:
Android has released a security library with EncryptedSharedPreferences in their Jetpack library.
Edit: With version v1.1.0 you can support Lollipop (API level 21) and above
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
// use the shared preferences and editor as you normally would
SharedPreferences.Editor editor = sharedPreferences.edit();
Google has released EncryptedSharedPreferences
as part of it's androidx, I believe this should be the preferable way of encrypting the preferences.
See https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences