Sitemap
Javarevisited

A humble place to learn Java and Programming better.

How to Use the Android Keystore for Secure Data Storage

--

If you’re building an Android app that handles sensitive data — like passwords, API keys, or personal information — you’ve probably wondered how to store that data securely. Good news! Android provides a built-in solution for this: the Android Keystore.

android keystore

In this guide, I’ll walk you through how to use the Android Keystore to store sensitive data securely in your app. Don’t worry — I’ll break it down step by step, and you don’t need to be a security expert to follow along.

What Is the Android Keystore?

Simply put, the Android Keystore is a system that allows you to store cryptographic keys (like encryption keys) in a secure and isolated environment. The big win here is that even if someone gains access to your app’s storage, they won’t be able to get their hands on those keys. Android keeps them tucked away where even your app can’t touch them directly.

Why Use the Keystore?

Storing sensitive information in plain text on the device is a big no-no. Encrypting your data is important, but managing the encryption keys is even more critical. The Android Keystore ensures:
- Keys are hardware-backed (if supported by the device). This means keys are generated and stored inside secure hardware, making it much harder to extract them.
- Keys can’t be exported. Once a key is in the Keystore, it can only be used for operations like encryption and decryption. The raw key itself is never accessible.
- Customizable access controls. You can specify when and how a key can be used, like requiring biometric authentication (fingerprint or face unlock) to use the key.

Now that we know why the Keystore is awesome, let’s dive into how to use it.

Setting Up the Android Keystore

To start, we’ll generate a cryptographic key using the Android Keystore, then use that key to encrypt and decrypt data.

Step 1: Generate a Key

First, you’ll need to generate a key pair (public and private) or a symmetric key (like AES) depending on your use case. Here’s how you can generate an AES key using the `KeyGenerator` class:

KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyGenerator.init(
new KeyGenParameterSpec.Builder("MySecureKey",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
);
SecretKey secretKey = keyGenerator.generateKey();

In this code:
- We’re using `KeyGenerator` to create a key for AES encryption.
- The key is stored in the Android Keystore with an alias (`”MySecureKey”`) to identify it later.
- We’re specifying that this key can be used for both encryption and decryption.

Step 2: Encrypt Data

Once we’ve generated our key, we can use it to encrypt data. Here’s a simple example of how to do that:

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] iv = cipher.getIV(); // Initialization vector
byte[] encryptedData = cipher.doFinal("MySensitiveData".getBytes());

In this example:
- We initialize the `Cipher` with the AES algorithm in GCM block mode (GCM is secure and recommended).
- `cipher.doFinal()` performs the encryption and returns the encrypted byte array.

Step 3: Decrypt Data

To decrypt the data, we need the same key (which is securely stored in the Keystore) and the initialization vector (IV) that was generated during encryption:

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
byte[] decryptedData = cipher.doFinal(encryptedData);
String decryptedString = new String(decryptedData);

Here:
- We use the same IV that was generated during encryption to initialize the cipher for decryption.
- The decrypted data is returned as a byte array, which we convert back into a string.

Step 4: Handle Key Access Controls

One of the cool features of the Android Keystore is the ability to control access to the keys. For example, you can require user authentication (like biometrics) before the key can be used:

new KeyGenParameterSpec.Builder("MySecureKey", 
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setUserAuthenticationRequired(true) // Require biometric auth
.build();

With this configuration, the user will need to authenticate before the key can be used. This adds an extra layer of protection, especially for sensitive apps like banking or healthcare.

Wrapping Up

And that’s it! You’ve just learned how to use the Android Keystore to securely generate, store, and use cryptographic keys for encrypting data in your app. The best part? All of this happens under the hood, and the keys never leave the secure hardware environment.

Key Takeaways:

  1. The Android Keystore is a secure, hardware-backed system for storing cryptographic keys.
  2. It ensures that keys are isolated from the rest of the system, making it hard for attackers to steal them.
  3. You can add extra layers of security, like requiring biometric authentication to access the keys.

Now that you’ve got the basics down, you can start integrating these techniques into your app to keep your users’ data safe and sound!

Happy coding!

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Mouad Oumous
Mouad Oumous

Written by Mouad Oumous

Java/Kotlin And Android Developer

No responses yet