Data Encryption on Android with Jetpack Security

Nwokocha Wisdom Maduabuchi
2 min readApr 26, 2020

--

Securing our data/files is essential in every Android application. In this tutorial, I will show you step by step how to encrypt your data using Jetpack Security( SharePreference).

So, let’s get started.

Jetpack Security Library

The Jetpack Security (JetSec) crypto library provides abstractions for encrypting Files and SharedPreferences objects. The library promotes the use of the AndroidKeyStore while using safe and well-known cryptographic primitives. Using EncryptedFile and EncryptedSharedPreferences allows you to locally protect files that may contain sensitive data, API keys, OAuth tokens, and other types of secrets.

Declaring dependencies

To add a dependency on Security, you must add the Google Maven repository to your project. Read Google’s Maven repository for more information.

Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

dependencies {
implementation "androidx.security:security-crypto:1.0.0-rc01"
}

New feature highlights

  • EncryptedFile, provides encrypted input and output streams to read/write encrypted data to a File.
  • EncryptedSharedPreferences, provides an implementation of SharedPreferences that automatically encrypts/decrypts all keys and values.
  • It provides a simple key generation via MasterKeys.

Steps to setup Jetpack Security in your android project

Step 1:

Create or retrieve the Master Key for encryption/decryption

val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

Step 2:

Initialize/open an instance of EncryptedSharedPreferences

val sharedPreferences = EncryptedSharedPreferences.create(
"PreferencesFilename",
masterKeyAlias,
applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)

Step 3:

Save data to the EncryptedSharedPreferences as usual

sharedPreferences.edit()
.putString("DATA", getencrpty.text.toString())
.apply()

Step 4:

Read data from EncryptedSharedPreferences as usual

val value = sharedPreferences.getString("DATA", "tea")
showtext.text = value

Step 5:

Edit from EncryptedSharedPreference

val sharedPrefsEditor = sharedPreferences.edit()

Conclusion

Jetpack Security provides high security of data to users. it's easy to configure and its recommended in every android application that deals with SharedPreferences and Files.

Github: https://github.com/wise4rmgod/JetPackSecurityExample

--

--

Nwokocha Wisdom Maduabuchi
Nwokocha Wisdom Maduabuchi

Written by Nwokocha Wisdom Maduabuchi

A software engineer with considerable experience in mobile development, native Android, and IOS development(Xcode), flutter dev, technical writing and community

No responses yet