Nerd For Tech
Published in

Nerd For Tech

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

Depedency for security library

Just sync your project and we are good to go.

  • Now you can easily create the Encrypted SharedPrefernces instance :
Creating Encypted SharedPreferences
  • 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.
Save string value in SharedPreferences
  • 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.

Stay in Touch :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nav Singh 🇨🇦

Google Developer Expert for Android | Mobile Software Engineer at Manulife | GDG Organizer at GDG Montreal