直接前往內容

最常造訪的網頁

最近瀏覽的網頁

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

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

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

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 (secp224r1), 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

Additional code samples

The Android AsymmetricFingerprintDialog, Android BasicAndroidKeyStore, and Android ConfirmCredential samples further demonstrate the use of the APIs covered on this page.

本網站使用 Cookie 儲存你在此指定的語言和顯示選項偏好設定。

掌握有關 Android 開發人員的最新消息和實用訣竅,協助你製作最受歡迎的 Google Play 內容。

* 必填欄位

訂閱成功!

在 WeChat 上追蹤 Google Developers

你要以瀏覽這個網站嗎?

你要求以顯示這個網頁,但你為此網站指定的語言偏好設定為

是否要變更語言偏好設定並改用瀏覽網站?稍後如要變更語言偏好設定,請利用位在每個網頁最下方的語言選單來調整設定。

你的 API 層級必須達 以上才能存取這個級別

本說明文件已隱藏,因為你為該文件選取的 API 層級為 。使用左側導覽列上方的選取工具即可變更說明文件的 API 層級。

如需進一步瞭解如何為應用程式指定 API 層級的相關資訊,請參閱 Supporting Different Platform Versions (支援不同的平台版本) (英文)。

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)