How to Encrypt Data Safely on the Device and Use the Android KeyStore?
Last Updated :
19 Nov, 2021
We deal with a great number of data in Android. Data from one activity is used in a different activity or fragment. For example, when some data changes, we can modify the UI of an application. So, the main concept is to have efficient communication between the data and the application's UI, and we all know that the ideal way to do it is to use Android Jetpack's LiveData.
Security Library in Jetpack
We will be using the Jetpack Security Library, which can be trusted as it's backed by good, it was also launched in 2019 making it relatively new. It even allows securing the shared_prefs and other data. It maintains a solid level of security by striking a balance between excellent encryption and fast performance. So we simply need to use the Jetpack Security library. Why utilize this Android Jetpack Security Library when the Android operating system is incredibly safe and we have a separate file-based encryption solution?
There are a number of causes for this, including:
- Even if you have full disc encryption, the file system on a rooted Android device is unlocked, and the data is easily accessible by an attacker.
- Another argument could be that you don't want even your users to have access to your application's keys or tokens.
dependencies {
...
implementation 'androidx.security:security-crypto:{latest-version}'
}
Management Personnel
We need to keep track of the keys we use in our Android app. So, on Android, we have something called the Android Keystore System, which protects our keys from being exploited by others. We have a MasterKeys class in Jetpack Security that allows us to construct a private key (by default, AES256 is used). Essentially, this class provides easy-to-use methods for creating and retrieving master keys from the Android Keystore.
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
We're utilizing the block mode GCM SPEC with no padding in this case. You don't need any padding or blocking if you wish to encrypt a little piece of data the size of a key. When the data to be encrypted is larger than the size of a key, padding and blocking are used.
Encryption of files
You may encrypt your app's files using the Jetpack Security Library. To handle files of any size, it employs the Streaming AES algorithm. It's as simple as creating a file and then converting it to an encrypted file. If you want to write data to your encrypted file after acquiring it, you may use the openFileOutput() method, and if you want to read data from your encrypted file, you can use the openFileInput() method. The code for this is as follows:
val gfgKeyAlias= MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val file = File("ANY_FILE_NAME")
val encryptedFile = EncryptedFile.Builder(
file,
applicationContext,
gfgKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build()
encryptedFile.openFileOutput().use { outputStream ->
}
Encryption of SharedPreferences
We use SharedPreferences to store our data since it is simple to use, but it also makes it simple for attackers to obtain the key and value from SharedPreferences. As a result, we'll need to encrypt our SharedPreferences data, which we can achieve with EncryptedSharedPreferences, which is available for Android 6.0 and higher. Simply create or retrieve a Master Key from the AndroidKeyStore to use an EncryptedSharedPreference:
val gfgKeyAlias= MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
After obtaining the Master Key, create an instance of EncryptedSharedPreferences as follows:
val anySharedPrefs= EncryptedSharedPreferences.create(
"your_name_of_shared_prefs",
masterKeyAlias,
applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
Finally, as normal, you can store and read data from the EncryptedSharedPreferences:
val KEY_DATA = "SHARED_DATA"
val dataToSave = "Some raw values"
// storing the data
anySharedPrefs.edit()
.putString(SHARED_DATA, someDataBound)
.apply()
// reading
val sharedData = anySharedPrefs.getString(SHARED_DATA, "")
Similar Reads
How to Encrypt and Decrypt Text in Android Using Cryptography?
Cryptography is a technique of securing information and communications through the use of codes so that only those people for whom the information is intended can understand it and process it. Thus preventing unauthorized access to information. The prefix âcryptâ means âhiddenâ and suffix graphy mea
15+ min read
How to Encrypt and Decrypt Images in Android?
Many times when we are building an android application we have to encrypt the data entered by the user within the android application to maintain the data privacy and security of the application. Along with that we also have to decrypt the data to access it. In this article, we will take a look at H
7 min read
How to Save Data to the Firebase Realtime Database in Android?
Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
7 min read
How to Generate SHA-1 Fingerprint of Keystore Certificate in Android Studio?
SHA-1 stands for Secure Hash Algorithm 1 and it is used when you want to integrate google API into your app. There are multiple ways to SHA-1 Fingerprint but I'll show you the easiest way to get it. This is what SHA-1 Fingerprint looks like. Steps to Generate SHA-1 Fingerprint of Keystore Certificat
1 min read
How to Install and Add Data to Realm Database in Android?
Realm Database is a service which is provided by MongoDb which is used to store data in users device locally. With the help of this data can be stored easily in users' devices and can be accessed easily. We can use this database to store data in the user's device itself. This is a series of 4 articl
8 min read
Storage System to Store Data in Android
We employ some form of storage in Android to retain the data permanently (until destroyed) for future reference. Android Storage System is the name given to these storage systems. Internal storage, external storage, shared preferences, database, and shared storage are some of the storage options off
5 min read
How to Access Data or Data Folder in an Android Device?
Android Operating System offers several storage methods to save your app data and images, audio files, docs, etc. App-specific storage: It only stores the data that is used by your App.Shared Storage: It stores files including images and documents.Databases: It provides a local Database for your app
7 min read
How to Connect an Android Phone to Linux via KDE Connect?
Nowadays while working on a PC most of the time we need to use our phones to transfer data and files to or from a computer. Therefore there is always a need for software that connects our mobile phones to a  PC so that we can not only share our files between them but also gain complete remote contro
4 min read
How to Generate SHA1, MD5, and SHA-256 Keys in Android Studio?
SHA1, MD5, and SHA-256 are cryptographic functions that will convert your input to 160 bit (20 bytes) value. It is a secure key that is used to store very important data. In Android SHA1, MD5 and SA-256 keys are very important. If you want to add external APIs from Google such as Maps and other exte
3 min read
How to Create and Add Data to SQLite Database in Android?
SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
8 min read