Open In App

Android Jetpack Compose Encrypted Shared Preferences

Improve
Improve
Like Article
Like
Save
Share
Report

Many times we want to save the data within the android application. This data is in the form of text and we generally prefer to store this data in the shared preferences. Shared preferences are not secure as we can simply view the data stored within the shared preferences and can easily access data within that file. In this article, we will take a look at How to use Encrypted Shared Preferences in android to store data securely within the android application using Jetpack Compose.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it.

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors
val greenColor = Color(0xFF0F9D58)


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.newcanaryproject
 
import android.content.*
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
 
                    // on the below line we are specifying
                    // the theme as the scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying the top bar.
                        topBar = {
 
                            // inside top bar we are specifying
                            // background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are
                                // specifying title for our top bar.
                                title = {
 
                                    // in the top bar we are
                                    // specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling method to display UI
                        encryptedSharedPrefs(context = LocalContext.current)
                    }
                }
            }
        }
    }
}
 
@Composable
fun encryptedSharedPrefs(context: Context) {
    // on below line creating a variable for message.
    val name = remember {
        mutableStateOf("")
    }
    val age = remember {
        mutableStateOf("")
    }
 
    // on below line we are getting data from encrypted shared preferences.
    // on below line getting data from shared preferences.
    // creating a master key for encryption of shared preferences.
    val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
 
    // Initialize/open an instance of EncryptedSharedPreferences on below line.
    val sharedPreferences = EncryptedSharedPreferences.create(
        // passing a file name to share a preferences
        "preferences",
        masterKeyAlias,
        context,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
    // on below line creating a variable
    // to get the data from shared prefs.
    val nameStr = sharedPreferences.getString("name", "")
    val ageStr = sharedPreferences.getString("age", "")
 
    name.value = nameStr!!
    age.value = ageStr!!
 
    // on below line we are creating a column,
    Column(
        // on below line we are adding a modifier to it,
        modifier = Modifier
            .fillMaxSize()
            // on below line we are adding a padding.
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
 
        // on below line we are adding a text for heading.
        Text(
            // on below line we are specifying text
            text = "Encrypted Shared Preferences in Android",
            // on below line we are specifying text color,
            // font size and font weight
            color = greenColor,
            textAlign = TextAlign.Center,
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold
        )
 
        // on below line adding a spacer.
        Spacer(modifier = Modifier.height(10.dp))
        // on below line we are creating a text field
          // for our message number.
        TextField(
            // on below line we are specifying
            // value for our message text field.
            value = name.value,
            // on below line we are adding on
            // value change for text field.
            onValueChange = { name.value = it },
            // on below line we are adding place holder
              // as text as "Enter your email"
            placeholder = { Text(text = "Enter your name") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
 
        // on below line adding a spacer.
        Spacer(modifier = Modifier.height(10.dp))
        // on below line we are creating a text field
        // for our message number.
        TextField(
            // on below line we are specifying
            // value for our message text field.
            value = age.value,
            // on below line we are adding on
            // value change for text field.
            onValueChange = { age.value = it },
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your age") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
 
        // on below line adding a spacer.
        Button(
            onClick = {
                // on below line we are setting data in our shared preferences.
                // creating a master key for encryption of shared preferences.
                val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
 
                // Initialize/open an instance of EncryptedSharedPreferences on below line.
                val sharedPreferences = EncryptedSharedPreferences.create(
                    // passing a file name to share a preferences
                    "preferences",
                    masterKeyAlias,
                    context,
                    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
                )
                // on below line we are storing data in shared preferences file.
                sharedPreferences.edit().putString("name", name.value).apply()
                sharedPreferences.edit().putString("age", age.value).apply()
                // A toast is shown for user reference that the text is
                // copied to the clipboard
                Toast.makeText(context, "Saved Data..", Toast.LENGTH_SHORT).show()
 
            },
            // on below line adding a modifier for our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp)
        ) {
            // on below line adding a text for our button.
            Text(text = "Save data to encrypted shared preferences", textAlign = TextAlign.Center)
        }
    }
}


Now run your application to see the output of it. 

Output:

Now check out the below article to check the value stored in the shared preferences How to View Data Stored in Shared Preferences in Android Studio. As we are using encrypted shared preferences we will get to see the data in the encrypted form. In the preferences.xml file, we will get to see the below data in the encrypted format. Encrypted shared preferences make it secure to store the data in shared preferences so anyone cannot access the data within our shared preferences.

XML




<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="__androidx_security_crypto_encrypted_prefs_key_keyset__">12a9013fda3ad9629e457e786af33d62299f3e40b0d234b35d51caeb9dd852e86cadf569a1b71e1a2b08f45c3687f7b5c8690ef61592db47028bc61f8b0e89a2b8a8cedcfe27326088c2bd75674427765e8d4825c5016209c16b3fb9a350eea95ee654c6f3ab574be79938bdd51a2ca04836b9bf378980d8db8ab853d7660cb48c9624ea0e65f67a640ad553ab21742b8c19dfd8ab646dc75172afb6092d65fb2e40550b15a7ef9fd66ec1051a4408b3caec8d01123c0a30747970652e676f6f676c65617069732e636f6d2f676f6f676c652e63727970746f2e74696e6b2e4165735369764b6579100118b3caec8d012001</string>
    <string name="__androidx_security_crypto_encrypted_prefs_value_keyset__">128801e69614a11efdfecabc1373dca2f9c52833dc406c6f4dcbc9a95b2e8adb6e2ed1758801f4910118913da64fb6abc3fc517a52eab2d14bb3785baf63c9fedfb963aeb17cdc3ee0d01f4885f536199101f6c90e363d435f9a031ddc62c256da80180d641e8832879d8755ce2d78413b45369c5438fc0f45ab71d592f1dc882f2ef8a286d2c40ea239521a44088ff8b48b06123c0a30747970652e676f6f676c65617069732e636f6d2f676f6f676c652e63727970746f2e74696e6b2e41657347636d4b65791001188ff8b48b062001</string>
    <string name="ARG7JTOF1nkm5AihUyXNOZrgOd6UMUDHHQ==">AWFtPA/fzbiRvVNTUBcKNCCTuADQXWZZwbbNLxlH/Y9DrPUJV4xhG6M9WArIhpqk31yZOiP/1FU=</string>
    <string name="ARG7JTODMfPHwpPifph0Xsg2GazOFXr8">AWFtPA9JrkHjCvALALXIhZ8fUKSNAAPfPHQSXIb1CglN4SrvcXBZpktorQ==</string>
</map>




Last Updated : 10 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads