Android Keystore: Security, Management, and Best Practices in Android

  • The Android Keystore system protects cryptographic keys and sensitive data within the device, preventing their extraction and enabling secure operations.
  • It allows for advanced restrictions, such as the use of secure hardware, biometric authentication, and limiting the use and validity of keys.
  • Proper management of the .keystore signing file is critical to the integrity and security of any app published on Google Play.

Keystore Android system

Security on Android has never been more important than it is today. As our apps handle more sensitive information, the need to protect passwords, API keys, and personal data becomes a top priority. Fortunately, the Android system itself provides a robust and reliable mechanism: the Keystore system . If you're a developer or simply want to understand how this key piece of mobile security works, here's a comprehensive guide that will reveal all the essentials and much more.

In this article, you'll not only discover how the Android Keystore works, but you'll also learn advanced concepts about generating, managing, and using cryptographic keys, how to avoid common security pitfalls, how to automate key management in development teams, and why efficient key file management is vital for the integrity of any modern Android app. Get ready, because we're going to break down every detail clearly and in easy-to-understand language, without sacrificing any technical rigor.

What is the Android Keystore and what is it for?

The Android Keystore is essentially a kind of digital vault or safe where the operating system itself securely stores cryptographic keys. This system is designed to prevent these keys, used for both data encryption and application signing, from being extracted or manipulated, even if an attacker gains access to the app's file system or the device itself.

The great added value of the Keystore lies in the fact that the key material never leaves its secure container: when an application wants to perform a cryptographic operation (encrypt, decrypt, sign, verify), it delegates the operation to the system, which uses the internal key and returns the result, preventing direct access to the key value.

The use of each key can be restricted , for example, by requiring biometric or password authentication before the key can be used, allowing the level of security to be raised according to the needs of each app.

The Keystore system is the native and recommended solution for managing keys on Android with the highest possible security.

Main features and benefits of the Android Keystore

Android Keystore Features

  • Key isolation: Keys are not accessible outside the Keystore container, neither to the application itself nor to the device's file system (nor to root users).
  • Support for hardware-backed keys: If supported by the device, keys are generated and stored in secure hardware (such as TEE or StrongBox), providing resistance to physical and extraction attacks.
  • Customizable usage restrictions: Possibility of requiring biometric authentication (fingerprint, face) or screen lock before each use of the key.
  • Unable to export keys: Once created within the Keystore, keys cannot be extracted for use outside.
  • Support for multiple algorithms and sizes: AES, RSA, ECDSA, ECDH, HMAC, Triple DES, among others.
  • Integration with standard APIs: The Keystore is used by standard classes such as KeyStore, KeyGenerator, KeyPairGenerator y KeyChain (for system-wide credentials).

Why is it so important to manage the Keystore well?

The keystore not only protects against data theft, but also forms the basis for the authenticity and trustworthiness of an Android application. An app's key file (the familiar .jks or .keystore file) allows the APK to be signed, and only with this signature can versions be updated on Google Play. If this file is lost or compromised, an attacker could sign malicious apps in your name, or you would lose the ability to update your software.

Furthermore, the keys stored in the Keystore can encrypt sensitive data such as passwords, tokens, or personal information , helping to maintain privacy even if the device is attacked.

How does the Android Keystore work internally?

The Keystore system acts as an intermediary between the app and the secure hardware (if any), transparently managing the key lifecycle. When a key is generated, it is stored under an identifier alias and can only be used by accessing it through that alias; the key value is never obtained directly.

There are two main levels of protection:

  • Protection against external extraction: The key never leaves the secure environment. If a malicious app or user accesses the storage, they can only use the key through the system and cannot extract it.
  • Internal restrictions: The Keystore can limit the uses of each key to certain operations, periods, or require the user to authenticate before each use.

On devices with StrongBox or TEE , keys can be stored on dedicated chips or enclaves, providing maximum protection against physical attacks or malware.

Key types and common uses in Android Keystore

The keystore is used to sign applications, authenticate users, and encrypt internal data. It works with:

  • Symmetric keys (AES, HMAC): To encrypt and decrypt information on the device.
  • Asymmetric keys (RSA, ECDSA, ECDH): For digital signatures, key exchange and authentication.
  • Certificates: Associated with private keys for secure communication and authentication.

It also allows, in recent Android versions, the secure import of existing keys and the performance of attestations to prove that a key is protected by secure hardware.

Key Generation and Storage: Step by Step

key store

To create a key in the Keystore, you can use KeyGenerator for symmetric keys or KeyPairGenerator for asymmetric keys. Example for an AES key:

Example (Java):

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

What is achieved with this?

  • Generate an AES key stored under the alias “MySecureAlias”.
  • Restrict it to only be used for encryption and decryption.
  • Isolate the key and prevent its extraction or misuse.

For asymmetric keys, the process is similar but with KeyPairGenerator and specific parameters for each algorithm.

Manage passwords on mobile
Related article:
Ultimate Guide to Managing and Protecting Passwords on Android: Security, Apps, and Essential Tips

Advanced Keystore (.jks/.keystore) file automation and management

While the Keystore protects the keys on the device, secure management of the signature file (.jks or .keystore) is essential for signing apps and updating on Google Play.

A common and dangerous mistake is uploading the .keystore file and its passwords to code repositories . If someone gains access to them, they can sign counterfeit applications or compromise the official signature.

How to manage this safely?

  • Do not include key files in public or uncontrolled repos.
  • Use secret managers such as HashiCorp Vault, AWS Secrets Manager, Azure Key Vault to store and manage credentials.
  • Automate keystore recovery in build processes, using plugins that download the file only in secure environments.
  • Separate keystores by environment or project, controlling who has access to each one.
  • Using environment variables or local configuration files to avoid exposing credentials in version control.

Implementing security and best practices in development teams

Key protection is not only a technical issue, but also an organizational one. A common mistake is allowing all team members access to production keystores, which increases security risks and the likelihood of errors.

Some key recommendations:

  • Limit access and roles: Only those responsible for signing releases should have access to production keys.
  • Use centralized and secure storage, as cloud systems with controlled permissions and secure connections during build.
  • Set up automated processes in CI/CD, so that the keystore is downloaded only in the necessary environments and destroyed after use, reducing risks.

For example, in local.properties and in CI/CD, you can define:

# local.properties
connectionString=DefaultEndpointsProtocol=https;AccountName=yourProject;AccountKey=SuperSecret;EndpointSuffix=endpoint.com
containerName=keystore
keyStoreFileName=KeyStore.jks
supportDocumentFilename=SupportFile.json

Example of a Gradle plugin for remote Keystore management

An advanced option is to use a Gradle plugin that manages the download and configuration of the signature file from cloud storage, such as Azure Blob Storage. How does it work?

  • The plugin gets access to storage from your properties or variables, container name, keystore name, and password files name.
  • During the build process, download the files, sign the APK, and delete them if necessary.
  • Properties are not stored in the usual Gradle extension, but are read at the beginning to configure the signing process.

SupportFile.json example:

{
«storePassword»: «elPasswordDelStore»,
«keyAlias»: «ElAliasDeLaKave»,
«keyPassword»: «elPasswordDeLaClave»
}

Advanced Options: StrongBox, TEE, and Hardware Security

On newer devices, the Keystore can take advantage of advanced hardware security features:

  • Trusted Execution Environment (TEE): A secure enclave in the processor, isolated from the operating system where the keys are stored and used.
  • StrongBox: Dedicated hardware with its own CPU, storage, and resistance to physical and side-channel attacks.
  • Key Attestation: Allows you to demonstrate to remote systems that a key is protected in secure hardware.

To check if a key is hardware backed, use KeyInfo.getSecurityLevel() o KeyInfo.isInsideSecurityHardware().

Access control: biometric authentication and expiration

One of the main advantages of the Keystore is that you can limit the use of keys to specific conditions: require biometrics, PIN or pattern, and define validity times after authentication.

This is achieved by setUserAuthenticationRequired(true) and other parameters, so that each use requires additional user validation.

Additionally, if a new biometric is added, the key may be automatically invalidated or remain valid, depending on the configuration (setInvalidatedByBiometricEnrollment()).

Data encryption and decryption step by step

To encrypt sensitive data using the Keystore key, this flow is generally followed:

  1. Get or generate the key by its alias.
  2. Configure a Cipher in AES/GCM/NoPadding mode.
  3. Encrypt the data: cipher.init(Cipher.ENCRYPT_MODE, secretKey), extract the IV and encrypt with cipher.doFinal().
  4. Save the IV and encrypted data.
  5. To decrypt: initialize the Cipher with the IV and key, and use cipher.doFinal() to obtain the original text.

This method ensures that the key never leaves the secure environment, even if the encrypted data and IV are stored locally.

Input control and use of aliases

The system KeyStore Allows you to manage all keys via aliases, lists, check holdings, delete, or retrieve details. Use methods such as:

  • aliases(): List all aliases.
  • containsAlias(alias): Check if an alias exists.
  • deleteEntry(alias): Deletes a specific key.
  • getEntry(alias, protección): Recover the key under a specific alias and protection.
  • size(): Total number of keys stored.

Remember that aliases are case-sensitive, so it's a good idea to manage names carefully to avoid confusion.

Common mistakes and how to avoid them

  • Upload the .keystore file to the repositories: Very dangerous. Manage passwords with secure systems and avoid exposing credentials.
  • Sharing production keys between projects or environments: It can compromise the entire security if one key is compromised.
  • Do not require authentication for sensitive operations: It is essential to protect actions with critical data using biometrics or PIN.
  • Local key dependency without automation: It is advisable to automate its management in large teams to reduce errors and risks.

Integration with modern technologies: Kotlin and Jetpack Compose

The Keystore system integrates seamlessly with Kotlin apps and frameworks like Jetpack Compose. From code, you can generate, encrypt, and decrypt data using Keystore functions, and display the encrypted or decrypted information dynamically in the UI. For more details, see our article on (https://www.todoandroid.es/strengthen-the-security-of-your-android-essential-apps/).

Simplified example in Compose:

@Composable
fun SecureDataScreen() {
val alias = "MyKey"
val text = "Secure Message".toByteArray()
...
Button(onClick = {
generateKey(alias)
val(encryption, iv) = encryptData(alias, text)
val decrypted = decryptData(alias, cipher, iv)
...
}) {
Text("Encrypt and Decrypt")
}
}

How to generate a keystore file to sign your app?

To create a .keystore file to publish on Google Play, follow these steps from Android Studio or the command line:

  1. Under “Build,” select “Generate Signed Bundle/APK.”
  2. Follow the wizard, define aliases and passwords.
  3. Save the .jks file in a safe place.
  4. Optionally, export the public key in PEM format to share it if needed.
  5. Upload the public key to the Google Play Console under “App signing.”

The future of key management on Android

Hardware-based security, advanced biometric authentication, and integration with professional secrets management systems will become increasingly common on Android. To learn more about strengthening the security of your apps, we recommend reviewing [link/reference].

Investing in good Keystore management, using automation and best practices, ensures that your apps and users are protected over the long term.

Mastering keystore use and applying best practices for managing it are fundamental steps to maintaining the integrity, confidentiality, and trust of your Android applications. Protecting your keys is the foundation of an effective and reliable security strategy in mobile development.


Add as preferred source in Google