Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaEncrypted Shared Preferences in Android

Encrypted Shared Preferences in Android

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. To make the data stored in shared preferences secure we use encrypted share preferences which are more secure and the data stored in them is encrypted. Anyone cannot read the data within the file easily. In this article, we will take a look at How to implement encrypted shared preferences in android.

Note: This Android article covered in both Java and Kotlin languages. 

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.

Step 2: Adding dependency in build.gradle file

Navigate to app>build.gradle and add below dependency in the dependencies section. 

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

After adding the dependency sync your project to install it. 

Step 3: Working with the activity_main.xml file

Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--edit text to enter amount-->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/idTILName"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="20dp"
        android:hint="Enter your name"
        android:padding="5dp"
        android:textColorHint="@color/black"
        app:hintTextColor="@color/black">
 
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/idEdtName"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:ems="10"
            android:importantForAutofill="no"
            android:inputType="text"
            android:textColor="@color/black"
            android:textColorHint="@color/black"
            android:textSize="14sp" />
    </com.google.android.material.textfield.TextInputLayout>
 
    <!--edit text to enter age-->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/idTiLAge"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="Enter your age"
        android:padding="5dp"
        android:textColorHint="@color/black"
        app:hintTextColor="@color/black">
 
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/idEdtAge"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:ems="10"
            android:importantForAutofill="no"
            android:inputType="phone"
            android:textColor="@color/black"
            android:textColorHint="@color/black"
            android:textSize="14sp" />
    </com.google.android.material.textfield.TextInputLayout>
 
</LinearLayout>


Step 4: Working with the MainActivity file 

Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.draganddrop
 
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.google.android.material.textfield.TextInputEditText
 
class MainActivity : AppCompatActivity() {
 
    // creating variables for edit text, button and text views.
    lateinit var nameEdt: TextInputEditText
    lateinit var ageEdt: TextInputEditText
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // initializing variables with ids.
        nameEdt = findViewById(R.id.idEdtName)
        ageEdt = findViewById(R.id.idEdtAge)
    }
 
    override fun onResume() {
        super.onResume()
        // 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,
            applicationContext,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )
        // on below line creating a variable
        // to get the data from shared prefs.
        val name = sharedPreferences.getString("name", "")
        val age = sharedPreferences.getString("age", "")
 
        // on below line we are setting data
        // to our name and age edit text.
        nameEdt.setText(name)
        ageEdt.setText(age)
    }
 
    override fun onPause() {
        super.onPause()
        // 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,
            applicationContext,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )
        // on below line we are storing data in shared preferences file.
        sharedPreferences.edit().putString("name", nameEdt.text.toString()).apply()
        sharedPreferences.edit().putString("age", ageEdt.text.toString()).apply()
    }
}


Java




package com.gtappdevelopers.textencryptionjava;
 
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKeys;
import com.google.android.material.textfield.TextInputEditText;
 
public class MainActivity extends AppCompatActivity {
   
    private TextInputEditText nameEdt, ageEdt;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing variables with ids.
        nameEdt = findViewById(R.id.idEdtName);
        ageEdt = findViewById(R.id.idEdtage);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        // on below line getting data from shared preferences.
        // creating a master key for encryption of shared preferences.
        String masterKeyAlias = null;
        try {
            masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        // Initialize/open an instance of
        // EncryptedSharedPreferences on below line.
        try {
            // on below line initializing our encrypted
            // shared preferences and passing our key to it.
            EncryptedSharedPreferences sharedPreferences = (EncryptedSharedPreferences) EncryptedSharedPreferences.create(
                    // passing a file name to share a preferences
                    "preferences",
                    masterKeyAlias,
                    getApplicationContext(),
                    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );
               
            // on below line creating a variable to
            // get the data from shared prefs.
            String name = sharedPreferences.getString("name", "");
            String age = sharedPreferences.getString("age", "");
 
            // on below line we are setting data
            // to our name and age edit text.
            nameEdt.setText(name);
            ageEdt.setText(age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        // on below line storing data to our shared prefs.
 
        // creating a master key for
        // encryption of shared preferences.
        String masterKeyAlias = null;
        try {
            masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Initialize/open an instance of
        // EncryptedSharedPreferences on below line.
        try {
            // on below line initializing our encrypted
            // shared preferences and passing our key to it.
            EncryptedSharedPreferences sharedPreferences = (EncryptedSharedPreferences) EncryptedSharedPreferences.create(
                    // passing a file name to share a preferences
                    "preferences",
                    masterKeyAlias,
                    getApplicationContext(),
                    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );
 
            // on below line we are storing data in shared preferences file.
            sharedPreferences.edit().putString("name", nameEdt.getText().toString()).apply();
            sharedPreferences.edit().putString("age", ageEdt.getText().toString()).apply();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}


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>


RELATED ARTICLES

Most Popular

Recent Comments