Show navigation Hide navigation

Android Keystore System

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 as well as the Android Keystore provider feature that was introduced in Android 4.3 (API level 18). 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 will not be able to 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 of KeyInfo.isInsideSecurityHardware().

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 can not 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 does not 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().

Choosing 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.

Using 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.

Generating 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. You can replace the certificate at a later time with a certificate signed by a Certificate Authority.

To generate the key, use a KeyPairGenerator with KeyPairGeneratorSpec:

/*
 * 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();

Generating a New Secret Key

To generate the key, use a KeyGenerator with KeyGenParameterSpec.

Working with Keystore Entries

Using the AndroidKeyStore provider takes place through all the standard KeyStore APIs.

Listing Entries

List entries in the keystore by calling the aliases() method:

/*
 * Load the Android KeyStore instance using the the
 * "AndroidKeyStore" provider to list out what entries are
 * currently stored.
 */
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
Enumeration<String> aliases = ks.aliases();

Signing and Verifying Data

Sign data by fetching the KeyStore.Entry from the keystore and using the Signature APIs, such as sign():

/*
 * 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:

/*
 * 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);

Requiring 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, fingerprint).

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, it is configured to operate in one of the two modes:

  • User authentication authorizes the use of keys for a duration of time. All keys in this mode are authorized for use as soon as the user unlocks the secure lock screen or confirms their secure lock screen credential using the KeyguardManager.createConfirmDeviceCredentialIntent flow. The duration for which the authorization remains valid is specific to each key, as specified using setUserAuthenticationValidityDurationSeconds during key generation or import. Such keys can only be generated or imported if the secure lock screen is enabled (see KeyguardManager.isDeviceSecure()). These keys become permanently invalidated once the secure lock screen is disabled (reconfigured to None, Swipe or other mode which does not authenticate the user) or forcibly reset (e.g. by a Device Administrator).
  • User authentication authorizes a specific cryptographic operation associated with one key. In this mode, each operation involving such a key must be individually authorized by the user. Currently, the only means of such authorization is fingerprint authentication: FingerprintManager.authenticate. Such keys can only be generated or imported if at least one fingerprint is enrolled (see FingerprintManager.hasEnrolledFingerprints). These keys become permanently invalidated once a new fingerprint is enrolled or all fingerprints are unenrolled.

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+
  • Supported sizes: 8--1024 (inclusive), must be multiple of 8
  • Default size: 160
HmacSHA224 23+
  • Supported sizes: 8--1024 (inclusive), must be multiple of 8
  • Default size: 224
HmacSHA256 23+
  • Supported sizes: 8--1024 (inclusive), must be multiple of 8
  • Default size: 256
HmacSHA384 23+
  • Supported sizes: 8--1024 (inclusive), must be multiple of 8
  • Default size: 384
HmacSHA512 23+
  • Supported sizes: 8--1024 (inclusive), must be multiple of 8
  • Default size: 512

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 as KeyPairGenerator and KeyGenerator.

KeyPairGenerator

Algorithm Supported (API Levels) Notes
DSA 19–22
EC 23+
  • Supported sizes: 224, 256, 384, 521
  • Supported named curves: P-224 (secp256r1), P-256 (aka secp256r1 and prime256v1), P-384 (aka secp384r1), P-521 (aka secp521r1)

Prior to API Level 23, EC keys can be generated using KeyPairGenerator of algorithm "RSA" initialized KeyPairGeneratorSpec whose key type is set to "EC" using setKeyType(String). EC curve name cannot be specified using this method -- a NIST P-curve is automatically chosen based on the requested key size.

RSA 18+
  • Supported sizes: 512, 768, 1024, 2048, 3072, 4096
  • Supported public exponents: 3, 65537
  • Default public exponent: 65537

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