The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Once keys are in the keystore, they can be used for cryptographic operations with the key material remaining non-exportable. Moreover, it offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes. See Security Features section for more information.
The Keystore system is used by the
KeyChain
API, introduced in Android 4.0 (API level 14); the Android Keystore provider
feature, introduced in Android 4.3 (API level 18); and the
Security library, available as part of
Jetpack. This document goes over when and how to use the Android Keystore
provider.
Security features
Android Keystore system protects key material from unauthorized use. Firstly, Android Keystore mitigates unauthorized use of key material outside of the Android device by preventing extraction of the key material from application processes and from the Android device as a whole. Secondly, Android KeyStore mitigates unauthorized use of key material on the Android device by making apps specify authorized uses of their keys and then enforcing these restrictions outside of the apps' processes.
Extraction prevention
Key material of Android Keystore keys is protected from extraction using two security measures:
- Key material never enters the application process. When an application performs cryptographic operations using an Android Keystore key, behind the scenes plaintext, ciphertext, and messages to be signed or verified are fed to a system process which carries out the cryptographic operations. If the app's process is compromised, the attacker may be able to use the app's keys but cannot extract their key material (for example, to be used outside of the Android device).
- Key material may be bound to the secure hardware (e.g., Trusted Execution Environment (TEE),
Secure Element (SE)) of the Android device. When this feature is enabled for a key, its key
material is never exposed outside of secure hardware. If the Android OS is compromised or an
attacker can read the device's internal storage, the attacker may be able to use any app's Android
Keystore keys on the Android device, but not extract them from the device. This feature is enabled
only if the device's secure hardware supports the particular combination of key algorithm, block
modes, padding schemes, and digests with which the key is authorized to be used. To check whether
the feature is enabled for a key, obtain a
KeyInfo
for the key and inspect the return value ofKeyInfo.isInsideSecurityHardware()
.
Hardware security module
Supported devices running Android 9 (API level 28) or higher installed can have a StrongBox Keymaster, an implementation of the Keymaster HAL that resides in a hardware security module. The module contains the following:
- Its own CPU.
- Secure storage.
- A true random-number generator.
- Additional mechanisms to resist package tampering and unauthorized sideloading of apps.
When checking keys stored in the StrongBox Keymaster, the system corroborates a key's integrity with the Trusted Execution Environment (TEE).
To support low-power StrongBox implementations, a subset of algorithms and key sizes are supported:
- RSA 2048
- AES 128 and 256
- ECDSA P-256
- HMAC-SHA256 (supports key sizes between 8 bytes and 64 bytes, inclusive)
- Triple DES 168
When generating or importing keys using the
KeyStore
class, you indicate a
preference for storing the key in the StrongBox Keymaster by passing true
to
the
setIsStrongBoxBacked()
method.
Key use authorizations
To mitigate unauthorized use of keys on the Android device, Android Keystore lets apps specify authorized uses of their keys when generating or importing the keys. Once a key is generated or imported, its authorizations cannot be changed. Authorizations are then enforced by the Android Keystore whenever the key is used. This is an advanced security feature which is generally useful only if your requirements are that a compromise of your application process after key generation/import (but not before or during) cannot lead to unauthorized uses of the key.
Supported key use authorizations fall into the following categories:
- cryptography: authorized key algorithm, operations or purposes (encrypt, decrypt, sign, verify), padding schemes, block modes, digests with which the key can be used;
- temporal validity interval: interval of time during which the key is authorized for use;
- user authentication: the key can only be used if the user has been authenticated recently enough. See Requiring User Authentication For Key Use.
As an additional security measure, for keys whose key material is inside secure hardware (see
KeyInfo.isInsideSecurityHardware()
)
some key use authorizations may be enforced by secure hardware, depending on the Android device.
Cryptographic and user authentication authorizations are likely to be enforced by secure hardware.
Temporal validity interval authorizations are unlikely to be enforced by the secure hardware
because it normally doesn't have an independent secure real-time clock.
Whether a key's user authentication authorization is enforced by the secure hardware can be
queried using
KeyInfo.isUserAuthenticationRequirementEnforcedBySecureHardware()
.
Choose between a keychain or the Android keystore provider
Use the KeyChain
API when you want
system-wide credentials. When an app requests the use of any credential
through the KeyChain
API, users get to
choose, through a system-provided UI, which of the installed credentials
an app can access. This allows several apps to use the
same set of credentials with user consent.
Use the Android Keystore provider to let an individual app store its own
credentials that only the app itself can access.
This provides a way for apps to manage credentials that are usable
only by itself while providing the same security benefits that the
KeyChain
API provides for system-wide
credentials. This method requires no user interaction to select the credentials.
Use Android keystore provider
To use this feature, you use the standard KeyStore
and KeyPairGenerator
or
KeyGenerator
classes along with the
AndroidKeyStore
provider introduced in Android 4.3 (API level 18).
AndroidKeyStore
is registered as a KeyStore
type for use with the KeyStore.getInstance(type)
method and as a provider for use with the KeyPairGenerator.getInstance(algorithm, provider)
and KeyGenerator.getInstance(algorithm, provider)
methods.
Generate a new private key
Generating a new PrivateKey
requires that
you also specify the initial X.509 attributes that the self-signed
certificate will have.
The Security library provides a default implementation for generating a valid symmetric key, as shown in the following snippet:
Kotlin
// Although you can define your own key generation parameter specification, it's // recommended that you use the value specified here. val mainKey = MasterKey.Builder(applicationContext) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build()
Java
// Although you can define your own key generation parameter specification, it's // recommended that you use the value specified here. Context context = getApplicationContext(); MasterKey mainKey = new MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build();
Alternatively, you can use
KeyStore.setKeyEntry
to replace the certificate at a later time with a certificate signed
by a Certificate Authority (CA).
To generate the key, use a KeyPairGenerator
with KeyPairGeneratorSpec
:
Kotlin
/* * Generate a new EC key pair entry in the Android Keystore by * using the KeyPairGenerator API. The private key can only be * used for signing or verification and only with SHA-256 or * SHA-512 as the message digest. */ val kpg: KeyPairGenerator = KeyPairGenerator.getInstance( KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore" ) val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY ).run { setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) build() } kpg.initialize(parameterSpec) val kp = kpg.generateKeyPair()
Java
/* * Generate a new EC key pair entry in the Android Keystore by * using the KeyPairGenerator API. The private key can only be * used for signing or verification and only with SHA-256 or * SHA-512 as the message digest. */ KeyPairGenerator kpg = KeyPairGenerator.getInstance( KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); kpg.initialize(new KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .build()); KeyPair kp = kpg.generateKeyPair();
Generate a new secret key
To generate the key, follow the same process as the one for generating a new private key. You use the Security library in each case.
Import encrypted keys more securely
Android 9 (API level 28) and higher allow you to import encrypted keys securely into the Keystore using an ASN.1‑encoded key format. The Keymaster then decrypts the keys in the Keystore, so the content of the keys never appears as plaintext in the device's host memory. This process provides additional key decryption security.
To support secure importing of encrypted keys into the Keystore, complete the following steps:
Generate a key pair that uses the
PURPOSE_WRAP_KEY
purpose. It's recommended that you add attestation to this key pair, as well.On a server or machine that you trust, generate the ASN.1 message that the
SecureKeyWrapper
should contain.The wrapper contains the following schema:
KeyDescription ::= SEQUENCE { keyFormat INTEGER, authorizationList AuthorizationList } SecureKeyWrapper ::= SEQUENCE { wrapperFormatVersion INTEGER, encryptedTransportKey OCTET_STRING, initializationVector OCTET_STRING, keyDescription KeyDescription, secureKey OCTET_STRING, tag OCTET_STRING }
Create a
WrappedKeyEntry
object, passing in the ASN.1 message as a byte array.Pass this
WrappedKeyEntry
object into the overload ofsetEntry()
that accepts aKeystore.Entry
object.
Work with keystore entries
Using the AndroidKeyStore
provider takes place through
all the standard KeyStore
APIs.
List entries
List entries in the keystore by calling the aliases()
method:
Kotlin
/* * Load the Android KeyStore instance using the * "AndroidKeyStore" provider to list out what entries are * currently stored. */ val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val aliases: Enumeration<String> = ks.aliases()
Java
/* * Load the Android KeyStore instance using the * "AndroidKeyStore" provider to list out what entries are * currently stored. */ KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); Enumeration<String> aliases = ks.aliases();
Sign and verify data
Sign data by fetching the KeyStore.Entry
from the keystore and using the
Signature
APIs, such as sign()
:
Kotlin
/* * Use a PrivateKey in the KeyStore to create a signature over * some data. */ val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val entry: KeyStore.Entry = ks.getEntry(alias, null) if (entry !is KeyStore.PrivateKeyEntry) { Log.w(TAG, "Not an instance of a PrivateKeyEntry") return null } val signature: ByteArray = Signature.getInstance("SHA256withECDSA").run { initSign(entry.privateKey) update(data) sign() }
Java
/* * Use a PrivateKey in the KeyStore to create a signature over * some data. */ KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); KeyStore.Entry entry = ks.getEntry(alias, null); if (!(entry instanceof PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); return null; } Signature s = Signature.getInstance("SHA256withECDSA"); s.initSign(((PrivateKeyEntry) entry).getPrivateKey()); s.update(data); byte[] signature = s.sign();
Similarly, verify data with the verify(byte[])
method:
Kotlin
/* * Verify a signature previously made by a PrivateKey in our * KeyStore. This uses the X.509 certificate attached to our * private key in the KeyStore to validate a previously * generated signature. */ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val entry = ks.getEntry(alias, null) as? KeyStore.PrivateKeyEntry if (entry == null) { Log.w(TAG, "Not an instance of a PrivateKeyEntry") return false } val valid: Boolean = Signature.getInstance("SHA256withECDSA").run { initVerify(entry.certificate) update(data) verify(signature) }
Java
/* * Verify a signature previously made by a PrivateKey in our * KeyStore. This uses the X.509 certificate attached to our * private key in the KeyStore to validate a previously * generated signature. */ KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); KeyStore.Entry entry = ks.getEntry(alias, null); if (!(entry instanceof PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); return false; } Signature s = Signature.getInstance("SHA256withECDSA"); s.initVerify(((PrivateKeyEntry) entry).getCertificate()); s.update(data); boolean valid = s.verify(signature);
Require user authentication for key use
When generating or importing a key into the AndroidKeyStore
you can specify that the key
is only authorized to be used if the user has been authenticated. The user is authenticated using a
subset of their secure lock screen credentials (pattern/PIN/password, biometric credentials).
This is an advanced security feature which is generally useful only if your requirements are that a compromise of your application process after key generation/import (but not before or during) cannot bypass the requirement for the user to be authenticated to use the key.
When a key is authorized to be used only if the user has been authenticated, you can call
setUserAuthenticationParameters()
to configure it to operate in one of the following modes:
- Authorize for a duration of time
- All keys are authorized for use as soon as the user authenticates using one of the credentials specified.
- Authorize for the duration of a specific cryptographic operation
Each operation involving a specific key must be individually authorized by the user.
Your app starts this process by calling
authenticate()
on an instance ofBiometricPrompt
.
For each key that you create, you can choose to support a
strong
biometric credential, a
lock screen
credential, or both types of credentials. To determine whether the user has set up the credentials
that your app's key relies on, call
canAuthenticate()
.
If a key only supports biometric credentials, the key is invalidated by default whenever new
biometric enrollments are added. You can configure the key to remain valid when new biometric
enrollments are added. To do so, pass false
into
setInvalidatedByBiometricEnrollment()
.
Learn more about how to add biometric authentication capabilities into your app, including how to show a biometric authentication dialog.
Supported algorithms
Cipher
Algorithm | Supported (API Levels) | Notes |
---|---|---|
AES/CBC/NoPadding | 23+ | |
AES/CBC/PKCS7Padding | 23+ | |
AES/CTR/NoPadding | 23+ | |
AES/ECB/NoPadding | 23+ | |
AES/ECB/PKCS7Padding | 23+ | |
AES/GCM/NoPadding | 23+ | Only 12-byte long IVs supported. |
RSA/ECB/NoPadding | 18+ | |
RSA/ECB/PKCS1Padding | 18+ | |
RSA/ECB/OAEPWithSHA-1AndMGF1Padding | 23+ | |
RSA/ECB/OAEPWithSHA-224AndMGF1Padding | 23+ | |
RSA/ECB/OAEPWithSHA-256AndMGF1Padding | 23+ | |
RSA/ECB/OAEPWithSHA-384AndMGF1Padding | 23+ | |
RSA/ECB/OAEPWithSHA-512AndMGF1Padding | 23+ | |
RSA/ECB/OAEPPadding | 23+ |
KeyGenerator
Algorithm | Supported (API Levels) | Notes |
---|---|---|
AES | 23+ | Supported sizes: 128, 192, 256 |
HmacSHA1 | 23+ |
|
HmacSHA224 | 23+ |
|
HmacSHA256 | 23+ |
|
HmacSHA384 | 23+ |
|
HmacSHA512 | 23+ |
|
KeyFactory
Algorithm | Supported (API Levels) | Notes |
---|---|---|
EC | 23+ | Supported key specs: KeyInfo (private key only),
ECPublicKeySpec (public key only),
X509EncodedKeySpec (public key only)
|
RSA | 23+ | Supported key specs: KeyInfo (private key only),
RSAPublicKeySpec (public key only),
X509EncodedKeySpec (public key only)
|
KeyStore
KeyStore supports the same key types asKeyPairGenerator
and
KeyGenerator
.
KeyPairGenerator
Algorithm | Supported (API Levels) | Notes |
---|---|---|
DSA | 19–22 | |
EC | 23+ |
Prior to API Level 23, EC keys can be generated using KeyPairGenerator of algorithm "RSA"
initialized |
RSA | 18+ |
|
Mac
Algorithm | Supported (API Levels) | Notes |
---|---|---|
HmacSHA1 | 23+ | |
HmacSHA224 | 23+ | |
HmacSHA256 | 23+ | |
HmacSHA384 | 23+ | |
HmacSHA512 | 23+ |
Signature
Algorithm | Supported (API Levels) | Notes |
---|---|---|
MD5withRSA | 18+ | |
NONEwithECDSA | 23+ | |
NONEwithRSA | 18+ | |
SHA1withDSA | 19–22 | |
SHA1withECDSA | 19+ | |
SHA1withRSA | 18+ | |
SHA1withRSA/PSS | 23+ | |
SHA224withDSA | 20–22 | |
SHA224withECDSA | 20+ | |
SHA224withRSA | 20+ | |
SHA224withRSA/PSS | 23+ | |
SHA256withDSA | 19–22 | |
SHA256withECDSA | 19+ | |
SHA256withRSA | 18+ | |
SHA256withRSA/PSS | 23+ | |
SHA384withDSA | 19–22 | |
SHA384withECDSA | 19+ | |
SHA384withRSA | 18+ | |
SHA384withRSA/PSS | 23+ | |
SHA512withDSA | 19–22 | |
SHA512withECDSA | 19+ | |
SHA512withRSA | 18+ | |
SHA512withRSA/PSS | 23+ |
SecretKeyFactory
Algorithm | Supported (API Levels) | Notes |
---|---|---|
AES | 23+ | Supported key specs: KeyInfo |
HmacSHA1 | 23+ | Supported key specs: KeyInfo |
HmacSHA224 | 23+ | Supported key specs: KeyInfo |
HmacSHA256 | 23+ | Supported key specs: KeyInfo |
HmacSHA384 | 23+ | Supported key specs: KeyInfo |
HmacSHA512 | 23+ | Supported key specs: KeyInfo |
Blog articles
See the blog entry Unifying Key Store Access in ICS.