EncryptedSharedPreferences example

EncryptedSharedPreferences class part of the Android Jetpack Security library, wraps the SharedPreferences class and automatically encrypts keys and values.

This new security library is still in alpha but will be available for all devices running Android 6.0 and above.

Creating the Application

In the following sections we are going to develop an Android app that shows how to use this class to encrypt a SharedPreferences content.

Fire up your Android Studio and create an empty Activity android application. In the Project configuration page set it up like in the image below.

Application configuration screen

Adding dependencies

Add the line below into your app build.gradle file in the dependencies section. As you can see, the library is still in early alpha stage.

implementation "androidx.security:security-crypto:1.0.0-alpha02"

MainActivity Class

All the application codes will reside in this class. See comments for explanations.

class MainActivity : AppCompatActivity() {

    //variables will be initialised in the onCreate function
    lateinit var masterKeyAlias: String
    lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

       //(1) create or retrieve masterkey from Android keystore 
       //masterkey is used to encrypt data encryption keys
        masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

       //(2) Get instance of EncryptedSharedPreferences class
       // as part of the params we pass the storage name, reference to 
       // masterKey, context and the encryption schemes used to 
       // encrypt SharedPreferences keys and values respectively.
        sharedPreferences = EncryptedSharedPreferences.create(
            "encrypted_shared_prefs",
            masterKeyAlias,
            MainActivity@this,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
       EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )

        encrypt_data.setOnClickListener { view -> encryptAndStore() }

        decrypt_data.setOnClickListener { view -> descryptAndShow() }

    }

    private fun encryptAndStore() {

        if(TextUtils.isEmpty(data.text.toString()))
            data.error = "Data cannot empty!!"

        //(3) Store text in sharepreferences as normally done
        //data will be encrypted as its stored
        sharedPreferences.edit()
        .putString("DATA",data.text.toString())
        .apply()

        Toast.makeText(MainActivity@this,"Data encrypted and 
        Stored!",Toast.LENGTH_SHORT).show()
    }

    //(4) retrieve text from storage and display it on a textview
    private fun descryptAndShow() {
        // get data as it is normally done
        var restored = sharedPreferences.getString("DATA","")
        data.setText(restored)
    }

}
Main Activity Screen

Sample Encrypted SharePreference content

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="ATpTKz5BPi+njv9nVtUT/4R/QXyvesg2VQ==">AUyI+58O3LiTDtvmNinpNXwNE0yfgvf515hpfVz4Uy4bkyP+WksUtDmW7aFn/Ep/408qsdpsdflhswjyMVdn4SsR</string>
    <string name="__androidx_security_crypto_encrypted_prefs_key_keyset__">12a901aea795d1513cd75b455387dd2a683f6154a793cfc681d759f7bfe10e11ba6b51b548bec8d59742db0fc5dc58d37e39c65e31845d9b263155e6308487b85b2f9ebe13e51cae3a52ecb2b57c2ba8ee4ed2bb519884a620d0fccb955cb7fc816530c53c5df132c8b7296be9a59e5800a9e9425a628e811684d1f5674bc62ff1f4298841f41124ad429235b2e2377bf37ddfab4fdb0d2700332843f9d8b009906e5e19616d37c5cb51f4e21a4408bed6ccd203123c0a30747970652e676f6f676c65617069732e636f6d2f676f6f676c652e63727970746f2e74696e6b2e4165735369764b6579100118bed6ccd2032001</string>
    <string name="__androidx_security_crypto_encrypted_prefs_value_keyset__">1288017448e753ed9dd642567ad6fdb2f05708e763b3a41841a523996b085750e49c6531d9763f7792e4d3a2798cd378279ef18bf94a8b64d3b9cabbeb2652f70273fce94de3d22cdc7d37105d72f38502c112e7c8b1964a99d92615058afa90b67cff796648fbc5af3f5ac46b23278485747c9aec9213a5c4af178f961783c0a1d046ad169e169f0851381a44089ff7a3e404123c0a30747970652e676f6f676c65617069732e636f6d2f676f6f676c652e63727970746f2e74696e6b2e41657347636d4b65791001189ff7a3e4042001</string>
</map>

encrypted_shared_prefs.xml contents

GitHub Link: https://github.com/choxxy/Encrypted-SharedPreference

Leave a Reply

Close Menu