• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.security.keystore;
18 
19 import android.annotation.IntRange;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.app.KeyguardManager;
23 import android.hardware.fingerprint.FingerprintManager;
24 import android.security.KeyStore;
25 import android.text.TextUtils;
26 
27 import java.math.BigInteger;
28 import java.security.KeyPairGenerator;
29 import java.security.Signature;
30 import java.security.cert.Certificate;
31 import java.security.spec.AlgorithmParameterSpec;
32 import java.util.Date;
33 
34 import javax.crypto.Cipher;
35 import javax.crypto.KeyGenerator;
36 import javax.crypto.Mac;
37 import javax.security.auth.x500.X500Principal;
38 
39 /**
40  * {@link AlgorithmParameterSpec} for initializing a {@link KeyPairGenerator} or a
41  * {@link KeyGenerator} of the <a href="{@docRoot}training/articles/keystore.html">Android Keystore
42  * system</a>. The spec determines authorized uses of the key, such as whether user authentication
43  * is required for using the key, what operations are authorized (e.g., signing, but not
44  * decryption), with what parameters (e.g., only with a particular padding scheme or digest), and
45  * the key's validity start and end dates. Key use authorizations expressed in the spec apply
46  * only to secret keys and private keys -- public keys can be used for any supported operations.
47  *
48  * <p>To generate an asymmetric key pair or a symmetric key, create an instance of this class using
49  * the {@link Builder}, initialize a {@code KeyPairGenerator} or a {@code KeyGenerator} of the
50  * desired key type (e.g., {@code EC} or {@code AES} -- see
51  * {@link KeyProperties}.{@code KEY_ALGORITHM} constants) from the {@code AndroidKeyStore} provider
52  * with the {@code KeyGenParameterSpec} instance, and then generate a key or key pair using
53  * {@link KeyGenerator#generateKey()} or {@link KeyPairGenerator#generateKeyPair()}.
54  *
55  * <p>The generated key pair or key will be returned by the generator and also stored in the Android
56  * Keystore under the alias specified in this spec. To obtain the secret or private key from the
57  * Android Keystore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)}
58  * or {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
59  * To obtain the public key from the Android Keystore use
60  * {@link java.security.KeyStore#getCertificate(String)} and then
61  * {@link Certificate#getPublicKey()}.
62  *
63  * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
64  * Keystore, generated private keys implement {@link java.security.interfaces.ECKey} or
65  * {@link java.security.interfaces.RSAKey} interfaces whereas public keys implement
66  * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
67  * interfaces.
68  *
69  * <p>For asymmetric key pairs, a self-signed X.509 certificate will be also generated and stored in
70  * the Android Keystore. This is because the {@link java.security.KeyStore} abstraction does not
71  * support storing key pairs without a certificate. The subject, serial number, and validity dates
72  * of the certificate can be customized in this spec. The self-signed certificate may be replaced at
73  * a later time by a certificate signed by a Certificate Authority (CA).
74  *
75  * <p>NOTE: If a private key is not authorized to sign the self-signed certificate, then the
76  * certificate will be created with an invalid signature which will not verify. Such a certificate
77  * is still useful because it provides access to the public key. To generate a valid signature for
78  * the certificate the key needs to be authorized for all of the following:
79  * <ul>
80  * <li>{@link KeyProperties#PURPOSE_SIGN},</li>
81  * <li>operation without requiring the user to be authenticated (see
82  * {@link Builder#setUserAuthenticationRequired(boolean)}),</li>
83  * <li>signing/origination at this moment in time (see {@link Builder#setKeyValidityStart(Date)}
84  * and {@link Builder#setKeyValidityForOriginationEnd(Date)}),</li>
85  * <li>suitable digest,</li>
86  * <li>(RSA keys only) padding scheme {@link KeyProperties#SIGNATURE_PADDING_RSA_PKCS1}.</li>
87  * </ul>
88  *
89  * <p>NOTE: The key material of the generated symmetric and private keys is not accessible. The key
90  * material of the public keys is accessible.
91  *
92  * <p>Instances of this class are immutable.
93  *
94  * <p><h3>Known issues</h3>
95  * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be
96  * enforced even for public keys. To work around this issue extract the public key material to use
97  * outside of Android Keystore. For example:
98  * <pre> {@code
99  * PublicKey unrestrictedPublicKey =
100  *         KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
101  *                 new X509EncodedKeySpec(publicKey.getEncoded()));
102  * }</pre>
103  *
104  * <p><h3>Example: NIST P-256 EC key pair for signing/verification using ECDSA</h3>
105  * This example illustrates how to generate a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair
106  * in the Android KeyStore system under alias {@code key1} where the private key is authorized to be
107  * used only for signing using SHA-256, SHA-384, or SHA-512 digest and only if the user has been
108  * authenticated within the last five minutes. The use of the public key is unrestricted (See Known
109  * Issues).
110  * <pre> {@code
111  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
112  *         KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
113  * keyPairGenerator.initialize(
114  *         new KeyGenParameterSpec.Builder(
115  *                 "key1",
116  *                 KeyProperties.PURPOSE_SIGN)
117  *                 .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
118  *                 .setDigests(KeyProperties.DIGEST_SHA256,
119  *                         KeyProperties.DIGEST_SHA384,
120  *                         KeyProperties.DIGEST_SHA512)
121  *                 // Only permit the private key to be used if the user authenticated
122  *                 // within the last five minutes.
123  *                 .setUserAuthenticationRequired(true)
124  *                 .setUserAuthenticationValidityDurationSeconds(5 * 60)
125  *                 .build());
126  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
127  * Signature signature = Signature.getInstance("SHA256withECDSA");
128  * signature.initSign(keyPair.getPrivate());
129  * ...
130  *
131  * // The key pair can also be obtained from the Android Keystore any time as follows:
132  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
133  * keyStore.load(null);
134  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
135  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
136  * }</pre>
137  *
138  * <p><h3>Example: RSA key pair for signing/verification using RSA-PSS</h3>
139  * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
140  * alias {@code key1} authorized to be used only for signing using the RSA-PSS signature padding
141  * scheme with SHA-256 or SHA-512 digests. The use of the public key is unrestricted.
142  * <pre> {@code
143  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
144  *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
145  * keyPairGenerator.initialize(
146  *         new KeyGenParameterSpec.Builder(
147  *                 "key1",
148  *                 KeyProperties.PURPOSE_SIGN)
149  *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
150  *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
151  *                 .build());
152  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
153  * Signature signature = Signature.getInstance("SHA256withRSA/PSS");
154  * signature.initSign(keyPair.getPrivate());
155  * ...
156  *
157  * // The key pair can also be obtained from the Android Keystore any time as follows:
158  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
159  * keyStore.load(null);
160  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
161  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
162  * }</pre>
163  *
164  * <p><h3>Example: RSA key pair for encryption/decryption using RSA OAEP</h3>
165  * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
166  * alias {@code key1} where the private key is authorized to be used only for decryption using RSA
167  * OAEP encryption padding scheme with SHA-256 or SHA-512 digests. The use of the public key is
168  * unrestricted.
169  * <pre> {@code
170  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
171  *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
172  * keyPairGenerator.initialize(
173  *         new KeyGenParameterSpec.Builder(
174  *                 "key1",
175  *                 KeyProperties.PURPOSE_DECRYPT)
176  *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
177  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
178  *                 .build());
179  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
180  * Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
181  * cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
182  * ...
183  *
184  * // The key pair can also be obtained from the Android Keystore any time as follows:
185  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
186  * keyStore.load(null);
187  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
188  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
189  * }</pre>
190  *
191  * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
192  * The following example illustrates how to generate an AES key in the Android KeyStore system under
193  * alias {@code key2} authorized to be used only for encryption/decryption in GCM mode with no
194  * padding.
195  * <pre> {@code
196  * KeyGenerator keyGenerator = KeyGenerator.getInstance(
197  *         KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
198  * keyGenerator.initialize(
199  *         new KeyGenParameterSpec.Builder("key2",
200  *                 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
201  *                 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
202  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
203  *                 .build());
204  * SecretKey key = keyGenerator.generateKey();
205  *
206  * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
207  * cipher.init(Cipher.ENCRYPT_MODE, key);
208  * ...
209  *
210  * // The key can also be obtained from the Android Keystore any time as follows:
211  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
212  * keyStore.load(null);
213  * key = (SecretKey) keyStore.getKey("key2", null);
214  * }</pre>
215  *
216  * <p><h3>Example: HMAC key for generating a MAC using SHA-256</h3>
217  * This example illustrates how to generate an HMAC key in the Android KeyStore system under alias
218  * {@code key2} authorized to be used only for generating an HMAC using SHA-256.
219  * <pre> {@code
220  * KeyGenerator keyGenerator = KeyGenerator.getInstance(
221  *         KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
222  * keyGenerator.initialize(
223  *         new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build());
224  * SecretKey key = keyGenerator.generateKey();
225  * Mac mac = Mac.getInstance("HmacSHA256");
226  * mac.init(key);
227  * ...
228  *
229  * // The key can also be obtained from the Android Keystore any time as follows:
230  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
231  * keyStore.load(null);
232  * key = (SecretKey) keyStore.getKey("key2", null);
233  * }</pre>
234  */
235 public final class KeyGenParameterSpec implements AlgorithmParameterSpec {
236 
237     private static final X500Principal DEFAULT_CERT_SUBJECT = new X500Principal("CN=fake");
238     private static final BigInteger DEFAULT_CERT_SERIAL_NUMBER = new BigInteger("1");
239     private static final Date DEFAULT_CERT_NOT_BEFORE = new Date(0L); // Jan 1 1970
240     private static final Date DEFAULT_CERT_NOT_AFTER = new Date(2461449600000L); // Jan 1 2048
241 
242     private final String mKeystoreAlias;
243     private final int mUid;
244     private final int mKeySize;
245     private final AlgorithmParameterSpec mSpec;
246     private final X500Principal mCertificateSubject;
247     private final BigInteger mCertificateSerialNumber;
248     private final Date mCertificateNotBefore;
249     private final Date mCertificateNotAfter;
250     private final Date mKeyValidityStart;
251     private final Date mKeyValidityForOriginationEnd;
252     private final Date mKeyValidityForConsumptionEnd;
253     private final @KeyProperties.PurposeEnum int mPurposes;
254     private final @KeyProperties.DigestEnum String[] mDigests;
255     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
256     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
257     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
258     private final boolean mRandomizedEncryptionRequired;
259     private final boolean mUserAuthenticationRequired;
260     private final int mUserAuthenticationValidityDurationSeconds;
261     private final byte[] mAttestationChallenge;
262     private final boolean mUniqueIdIncluded;
263     private final boolean mUserAuthenticationValidWhileOnBody;
264     private final boolean mInvalidatedByBiometricEnrollment;
265 
266     /**
267      * @hide should be built with Builder
268      */
KeyGenParameterSpec( String keyStoreAlias, int uid, int keySize, AlgorithmParameterSpec spec, X500Principal certificateSubject, BigInteger certificateSerialNumber, Date certificateNotBefore, Date certificateNotAfter, Date keyValidityStart, Date keyValidityForOriginationEnd, Date keyValidityForConsumptionEnd, @KeyProperties.PurposeEnum int purposes, @KeyProperties.DigestEnum String[] digests, @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings, @KeyProperties.SignaturePaddingEnum String[] signaturePaddings, @KeyProperties.BlockModeEnum String[] blockModes, boolean randomizedEncryptionRequired, boolean userAuthenticationRequired, int userAuthenticationValidityDurationSeconds, byte[] attestationChallenge, boolean uniqueIdIncluded, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment)269     public KeyGenParameterSpec(
270             String keyStoreAlias,
271             int uid,
272             int keySize,
273             AlgorithmParameterSpec spec,
274             X500Principal certificateSubject,
275             BigInteger certificateSerialNumber,
276             Date certificateNotBefore,
277             Date certificateNotAfter,
278             Date keyValidityStart,
279             Date keyValidityForOriginationEnd,
280             Date keyValidityForConsumptionEnd,
281             @KeyProperties.PurposeEnum int purposes,
282             @KeyProperties.DigestEnum String[] digests,
283             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
284             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
285             @KeyProperties.BlockModeEnum String[] blockModes,
286             boolean randomizedEncryptionRequired,
287             boolean userAuthenticationRequired,
288             int userAuthenticationValidityDurationSeconds,
289             byte[] attestationChallenge,
290             boolean uniqueIdIncluded,
291             boolean userAuthenticationValidWhileOnBody,
292             boolean invalidatedByBiometricEnrollment) {
293         if (TextUtils.isEmpty(keyStoreAlias)) {
294             throw new IllegalArgumentException("keyStoreAlias must not be empty");
295         }
296 
297         if (certificateSubject == null) {
298             certificateSubject = DEFAULT_CERT_SUBJECT;
299         }
300         if (certificateNotBefore == null) {
301             certificateNotBefore = DEFAULT_CERT_NOT_BEFORE;
302         }
303         if (certificateNotAfter == null) {
304             certificateNotAfter = DEFAULT_CERT_NOT_AFTER;
305         }
306         if (certificateSerialNumber == null) {
307             certificateSerialNumber = DEFAULT_CERT_SERIAL_NUMBER;
308         }
309 
310         if (certificateNotAfter.before(certificateNotBefore)) {
311             throw new IllegalArgumentException("certificateNotAfter < certificateNotBefore");
312         }
313 
314         mKeystoreAlias = keyStoreAlias;
315         mUid = uid;
316         mKeySize = keySize;
317         mSpec = spec;
318         mCertificateSubject = certificateSubject;
319         mCertificateSerialNumber = certificateSerialNumber;
320         mCertificateNotBefore = Utils.cloneIfNotNull(certificateNotBefore);
321         mCertificateNotAfter = Utils.cloneIfNotNull(certificateNotAfter);
322         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
323         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
324         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
325         mPurposes = purposes;
326         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
327         mEncryptionPaddings =
328                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
329         mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
330         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
331         mRandomizedEncryptionRequired = randomizedEncryptionRequired;
332         mUserAuthenticationRequired = userAuthenticationRequired;
333         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
334         mAttestationChallenge = Utils.cloneIfNotNull(attestationChallenge);
335         mUniqueIdIncluded = uniqueIdIncluded;
336         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
337         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
338     }
339 
340     /**
341      * Returns the alias that will be used in the {@code java.security.KeyStore}
342      * in conjunction with the {@code AndroidKeyStore}.
343      */
344     @NonNull
getKeystoreAlias()345     public String getKeystoreAlias() {
346         return mKeystoreAlias;
347     }
348 
349     /**
350      * Returns the UID which will own the key. {@code -1} is an alias for the UID of the current
351      * process.
352      *
353      * @hide
354      */
getUid()355     public int getUid() {
356         return mUid;
357     }
358 
359     /**
360      * Returns the requested key size. If {@code -1}, the size should be looked up from
361      * {@link #getAlgorithmParameterSpec()}, if provided, otherwise an algorithm-specific default
362      * size should be used.
363      */
getKeySize()364     public int getKeySize() {
365         return mKeySize;
366     }
367 
368     /**
369      * Returns the key algorithm-specific {@link AlgorithmParameterSpec} that will be used for
370      * creation of the key or {@code null} if algorithm-specific defaults should be used.
371      */
372     @Nullable
getAlgorithmParameterSpec()373     public AlgorithmParameterSpec getAlgorithmParameterSpec() {
374         return mSpec;
375     }
376 
377     /**
378      * Returns the subject distinguished name to be used on the X.509 certificate that will be put
379      * in the {@link java.security.KeyStore}.
380      */
381     @NonNull
getCertificateSubject()382     public X500Principal getCertificateSubject() {
383         return mCertificateSubject;
384     }
385 
386     /**
387      * Returns the serial number to be used on the X.509 certificate that will be put in the
388      * {@link java.security.KeyStore}.
389      */
390     @NonNull
getCertificateSerialNumber()391     public BigInteger getCertificateSerialNumber() {
392         return mCertificateSerialNumber;
393     }
394 
395     /**
396      * Returns the start date to be used on the X.509 certificate that will be put in the
397      * {@link java.security.KeyStore}.
398      */
399     @NonNull
getCertificateNotBefore()400     public Date getCertificateNotBefore() {
401         return Utils.cloneIfNotNull(mCertificateNotBefore);
402     }
403 
404     /**
405      * Returns the end date to be used on the X.509 certificate that will be put in the
406      * {@link java.security.KeyStore}.
407      */
408     @NonNull
getCertificateNotAfter()409     public Date getCertificateNotAfter() {
410         return Utils.cloneIfNotNull(mCertificateNotAfter);
411     }
412 
413     /**
414      * Returns the time instant before which the key is not yet valid or {@code null} if not
415      * restricted.
416      */
417     @Nullable
getKeyValidityStart()418     public Date getKeyValidityStart() {
419         return Utils.cloneIfNotNull(mKeyValidityStart);
420     }
421 
422     /**
423      * Returns the time instant after which the key is no longer valid for decryption and
424      * verification or {@code null} if not restricted.
425      */
426     @Nullable
getKeyValidityForConsumptionEnd()427     public Date getKeyValidityForConsumptionEnd() {
428         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
429     }
430 
431     /**
432      * Returns the time instant after which the key is no longer valid for encryption and signing
433      * or {@code null} if not restricted.
434      */
435     @Nullable
getKeyValidityForOriginationEnd()436     public Date getKeyValidityForOriginationEnd() {
437         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
438     }
439 
440     /**
441      * Returns the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
442      * Attempts to use the key for any other purpose will be rejected.
443      *
444      * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
445      */
getPurposes()446     public @KeyProperties.PurposeEnum int getPurposes() {
447         return mPurposes;
448     }
449 
450     /**
451      * Returns the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384} with which the
452      * key can be used or {@code null} if not specified.
453      *
454      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
455      *
456      * @throws IllegalStateException if this set has not been specified.
457      *
458      * @see #isDigestsSpecified()
459      */
460     @NonNull
getDigests()461     public @KeyProperties.DigestEnum String[] getDigests() {
462         if (mDigests == null) {
463             throw new IllegalStateException("Digests not specified");
464         }
465         return ArrayUtils.cloneIfNotEmpty(mDigests);
466     }
467 
468     /**
469      * Returns {@code true} if the set of digest algorithms with which the key can be used has been
470      * specified.
471      *
472      * @see #getDigests()
473      */
474     @NonNull
isDigestsSpecified()475     public boolean isDigestsSpecified() {
476         return mDigests != null;
477     }
478 
479     /**
480      * Returns the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OEAPPadding},
481      * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
482      * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
483      * rejected.
484      *
485      * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
486      */
487     @NonNull
getEncryptionPaddings()488     public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
489         return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
490     }
491 
492     /**
493      * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
494      * can be used when signing/verifying. Attempts to use the key with any other padding scheme
495      * will be rejected.
496      *
497      * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
498      */
499     @NonNull
getSignaturePaddings()500     public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
501         return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
502     }
503 
504     /**
505      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
506      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
507      * rejected.
508      *
509      * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
510      */
511     @NonNull
getBlockModes()512     public @KeyProperties.BlockModeEnum String[] getBlockModes() {
513         return ArrayUtils.cloneIfNotEmpty(mBlockModes);
514     }
515 
516     /**
517      * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
518      * different ciphertexts for the same plaintext every time. The formal cryptographic property
519      * being required is <em>indistinguishability under chosen-plaintext attack ({@code
520      * IND-CPA})</em>. This property is important because it mitigates several classes of
521      * weaknesses due to which ciphertext may leak information about plaintext.  For example, if a
522      * given plaintext always produces the same ciphertext, an attacker may see the repeated
523      * ciphertexts and be able to deduce something about the plaintext.
524      */
isRandomizedEncryptionRequired()525     public boolean isRandomizedEncryptionRequired() {
526         return mRandomizedEncryptionRequired;
527     }
528 
529     /**
530      * Returns {@code true} if the key is authorized to be used only if the user has been
531      * authenticated.
532      *
533      * <p>This authorization applies only to secret key and private key operations. Public key
534      * operations are not restricted.
535      *
536      * @see #getUserAuthenticationValidityDurationSeconds()
537      * @see Builder#setUserAuthenticationRequired(boolean)
538      */
isUserAuthenticationRequired()539     public boolean isUserAuthenticationRequired() {
540         return mUserAuthenticationRequired;
541     }
542 
543     /**
544      * Gets the duration of time (seconds) for which this key is authorized to be used after the
545      * user is successfully authenticated. This has effect only if user authentication is required
546      * (see {@link #isUserAuthenticationRequired()}).
547      *
548      * <p>This authorization applies only to secret key and private key operations. Public key
549      * operations are not restricted.
550      *
551      * @return duration in seconds or {@code -1} if authentication is required for every use of the
552      *         key.
553      *
554      * @see #isUserAuthenticationRequired()
555      * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
556      */
getUserAuthenticationValidityDurationSeconds()557     public int getUserAuthenticationValidityDurationSeconds() {
558         return mUserAuthenticationValidityDurationSeconds;
559     }
560 
561     /**
562      * Returns the attestation challenge value that will be placed in attestation certificate for
563      * this key pair.
564      *
565      * <p>If this method returns non-{@code null}, the public key certificate for this key pair will
566      * contain an extension that describes the details of the key's configuration and
567      * authorizations, including the content of the attestation challenge value. If the key is in
568      * secure hardware, and if the secure hardware supports attestation, the certificate will be
569      * signed by a chain of certificates rooted at a trustworthy CA key. Otherwise the chain will
570      * be rooted at an untrusted certificate.
571      *
572      * <p>If this method returns {@code null}, and the spec is used to generate an asymmetric (RSA
573      * or EC) key pair, the public key will have a self-signed certificate if it has purpose {@link
574      * KeyProperties#PURPOSE_SIGN}. If does not have purpose {@link KeyProperties#PURPOSE_SIGN}, it
575      * will have a fake certificate.
576      *
577      * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
578      * KeyGenParameterSpec with getAttestationChallenge returning non-null is used to generate a
579      * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
580      * {@link java.security.InvalidAlgorithmParameterException}.
581      *
582      * @see Builder#setAttestationChallenge(byte[])
583      */
getAttestationChallenge()584     public byte[] getAttestationChallenge() {
585         return Utils.cloneIfNotNull(mAttestationChallenge);
586     }
587 
588     /**
589      * @hide This is a system-only API
590      *
591      * Returns {@code true} if the attestation certificate will contain a unique ID field.
592      */
isUniqueIdIncluded()593     public boolean isUniqueIdIncluded() {
594         return mUniqueIdIncluded;
595     }
596 
597     /**
598      * Returns {@code true} if the key will remain authorized only until the device is removed from
599      * the user's body, up to the validity duration.  This option has no effect on keys that don't
600      * have an authentication validity duration, and has no effect if the device lacks an on-body
601      * sensor.
602      *
603      * <p>Authorization applies only to secret key and private key operations. Public key operations
604      * are not restricted.
605      *
606      * @see #isUserAuthenticationRequired()
607      * @see #getUserAuthenticationValidityDurationSeconds()
608      * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
609      */
isUserAuthenticationValidWhileOnBody()610     public boolean isUserAuthenticationValidWhileOnBody() {
611         return mUserAuthenticationValidWhileOnBody;
612     }
613 
614     /**
615      * Returns {@code true} if the key is irreversibly invalidated when a new fingerprint is
616      * enrolled or all enrolled fingerprints are removed. This has effect only for keys that
617      * require fingerprint user authentication for every use.
618      *
619      * @see #isUserAuthenticationRequired()
620      * @see #getUserAuthenticationValidityDurationSeconds()
621      * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
622      */
isInvalidatedByBiometricEnrollment()623     public boolean isInvalidatedByBiometricEnrollment() {
624         return mInvalidatedByBiometricEnrollment;
625     }
626 
627     /**
628      * Builder of {@link KeyGenParameterSpec} instances.
629      */
630     public final static class Builder {
631         private final String mKeystoreAlias;
632         private @KeyProperties.PurposeEnum int mPurposes;
633 
634         private int mUid = KeyStore.UID_SELF;
635         private int mKeySize = -1;
636         private AlgorithmParameterSpec mSpec;
637         private X500Principal mCertificateSubject;
638         private BigInteger mCertificateSerialNumber;
639         private Date mCertificateNotBefore;
640         private Date mCertificateNotAfter;
641         private Date mKeyValidityStart;
642         private Date mKeyValidityForOriginationEnd;
643         private Date mKeyValidityForConsumptionEnd;
644         private @KeyProperties.DigestEnum String[] mDigests;
645         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
646         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
647         private @KeyProperties.BlockModeEnum String[] mBlockModes;
648         private boolean mRandomizedEncryptionRequired = true;
649         private boolean mUserAuthenticationRequired;
650         private int mUserAuthenticationValidityDurationSeconds = -1;
651         private byte[] mAttestationChallenge = null;
652         private boolean mUniqueIdIncluded = false;
653         private boolean mUserAuthenticationValidWhileOnBody;
654         private boolean mInvalidatedByBiometricEnrollment = true;
655 
656         /**
657          * Creates a new instance of the {@code Builder}.
658          *
659          * @param keystoreAlias alias of the entry in which the generated key will appear in
660          *        Android KeyStore. Must not be empty.
661          * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
662          *        used. Attempts to use the key for any other purpose will be rejected.
663          *
664          *        <p>If the set of purposes for which the key can be used does not contain
665          *        {@link KeyProperties#PURPOSE_SIGN}, the self-signed certificate generated by
666          *        {@link KeyPairGenerator} of {@code AndroidKeyStore} provider will contain an
667          *        invalid signature. This is OK if the certificate is only used for obtaining the
668          *        public key from Android KeyStore.
669          *
670          *        <p>See {@link KeyProperties}.{@code PURPOSE} flags.
671          */
Builder(@onNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes)672         public Builder(@NonNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes) {
673             if (keystoreAlias == null) {
674                 throw new NullPointerException("keystoreAlias == null");
675             } else if (keystoreAlias.isEmpty()) {
676                 throw new IllegalArgumentException("keystoreAlias must not be empty");
677             }
678             mKeystoreAlias = keystoreAlias;
679             mPurposes = purposes;
680         }
681 
682         /**
683          * Sets the UID which will own the key.
684          *
685          * @param uid UID or {@code -1} for the UID of the current process.
686          *
687          * @hide
688          */
689         @NonNull
setUid(int uid)690         public Builder setUid(int uid) {
691             mUid = uid;
692             return this;
693         }
694 
695         /**
696          * Sets the size (in bits) of the key to be generated. For instance, for RSA keys this sets
697          * the modulus size, for EC keys this selects a curve with a matching field size, and for
698          * symmetric keys this sets the size of the bitstring which is their key material.
699          *
700          * <p>The default key size is specific to each key algorithm. If key size is not set
701          * via this method, it should be looked up from the algorithm-specific parameters (if any)
702          * provided via
703          * {@link #setAlgorithmParameterSpec(AlgorithmParameterSpec) setAlgorithmParameterSpec}.
704          */
705         @NonNull
setKeySize(int keySize)706         public Builder setKeySize(int keySize) {
707             if (keySize < 0) {
708                 throw new IllegalArgumentException("keySize < 0");
709             }
710             mKeySize = keySize;
711             return this;
712         }
713 
714         /**
715          * Sets the algorithm-specific key generation parameters. For example, for RSA keys this may
716          * be an instance of {@link java.security.spec.RSAKeyGenParameterSpec} whereas for EC keys
717          * this may be an instance of {@link java.security.spec.ECGenParameterSpec}.
718          *
719          * <p>These key generation parameters must match other explicitly set parameters (if any),
720          * such as key size.
721          */
setAlgorithmParameterSpec(@onNull AlgorithmParameterSpec spec)722         public Builder setAlgorithmParameterSpec(@NonNull AlgorithmParameterSpec spec) {
723             if (spec == null) {
724                 throw new NullPointerException("spec == null");
725             }
726             mSpec = spec;
727             return this;
728         }
729 
730         /**
731          * Sets the subject used for the self-signed certificate of the generated key pair.
732          *
733          * <p>By default, the subject is {@code CN=fake}.
734          */
735         @NonNull
setCertificateSubject(@onNull X500Principal subject)736         public Builder setCertificateSubject(@NonNull X500Principal subject) {
737             if (subject == null) {
738                 throw new NullPointerException("subject == null");
739             }
740             mCertificateSubject = subject;
741             return this;
742         }
743 
744         /**
745          * Sets the serial number used for the self-signed certificate of the generated key pair.
746          *
747          * <p>By default, the serial number is {@code 1}.
748          */
749         @NonNull
setCertificateSerialNumber(@onNull BigInteger serialNumber)750         public Builder setCertificateSerialNumber(@NonNull BigInteger serialNumber) {
751             if (serialNumber == null) {
752                 throw new NullPointerException("serialNumber == null");
753             }
754             mCertificateSerialNumber = serialNumber;
755             return this;
756         }
757 
758         /**
759          * Sets the start of the validity period for the self-signed certificate of the generated
760          * key pair.
761          *
762          * <p>By default, this date is {@code Jan 1 1970}.
763          */
764         @NonNull
setCertificateNotBefore(@onNull Date date)765         public Builder setCertificateNotBefore(@NonNull Date date) {
766             if (date == null) {
767                 throw new NullPointerException("date == null");
768             }
769             mCertificateNotBefore = Utils.cloneIfNotNull(date);
770             return this;
771         }
772 
773         /**
774          * Sets the end of the validity period for the self-signed certificate of the generated key
775          * pair.
776          *
777          * <p>By default, this date is {@code Jan 1 2048}.
778          */
779         @NonNull
setCertificateNotAfter(@onNull Date date)780         public Builder setCertificateNotAfter(@NonNull Date date) {
781             if (date == null) {
782                 throw new NullPointerException("date == null");
783             }
784             mCertificateNotAfter = Utils.cloneIfNotNull(date);
785             return this;
786         }
787 
788         /**
789          * Sets the time instant before which the key is not yet valid.
790          *
791          * <p>By default, the key is valid at any instant.
792          *
793          * @see #setKeyValidityEnd(Date)
794          */
795         @NonNull
setKeyValidityStart(Date startDate)796         public Builder setKeyValidityStart(Date startDate) {
797             mKeyValidityStart = Utils.cloneIfNotNull(startDate);
798             return this;
799         }
800 
801         /**
802          * Sets the time instant after which the key is no longer valid.
803          *
804          * <p>By default, the key is valid at any instant.
805          *
806          * @see #setKeyValidityStart(Date)
807          * @see #setKeyValidityForConsumptionEnd(Date)
808          * @see #setKeyValidityForOriginationEnd(Date)
809          */
810         @NonNull
setKeyValidityEnd(Date endDate)811         public Builder setKeyValidityEnd(Date endDate) {
812             setKeyValidityForOriginationEnd(endDate);
813             setKeyValidityForConsumptionEnd(endDate);
814             return this;
815         }
816 
817         /**
818          * Sets the time instant after which the key is no longer valid for encryption and signing.
819          *
820          * <p>By default, the key is valid at any instant.
821          *
822          * @see #setKeyValidityForConsumptionEnd(Date)
823          */
824         @NonNull
setKeyValidityForOriginationEnd(Date endDate)825         public Builder setKeyValidityForOriginationEnd(Date endDate) {
826             mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
827             return this;
828         }
829 
830         /**
831          * Sets the time instant after which the key is no longer valid for decryption and
832          * verification.
833          *
834          * <p>By default, the key is valid at any instant.
835          *
836          * @see #setKeyValidityForOriginationEnd(Date)
837          */
838         @NonNull
setKeyValidityForConsumptionEnd(Date endDate)839         public Builder setKeyValidityForConsumptionEnd(Date endDate) {
840             mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
841             return this;
842         }
843 
844         /**
845          * Sets the set of digests algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which
846          * the key can be used. Attempts to use the key with any other digest algorithm will be
847          * rejected.
848          *
849          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
850          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
851          * HMAC keys, the default is the digest associated with the key algorithm (e.g.,
852          * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
853          * for more than one digest.
854          *
855          * <p>For private keys used for TLS/SSL client or server authentication it is usually
856          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
857          * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
858          * a private key to sign it.
859          *
860          * <p>See {@link KeyProperties}.{@code DIGEST} constants.
861          */
862         @NonNull
setDigests(@eyProperties.DigestEnum String... digests)863         public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
864             mDigests = ArrayUtils.cloneIfNotEmpty(digests);
865             return this;
866         }
867 
868         /**
869          * Sets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OAEPPadding},
870          * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
871          * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
872          * rejected.
873          *
874          * <p>This must be specified for keys which are used for encryption/decryption.
875          *
876          * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
877          * is usually necessary to authorize the use of no/any padding
878          * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
879          * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
880          * required by some cipher suites, and some stacks request decryption using no padding
881          * whereas others request PKCS#1 padding.
882          *
883          * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
884          */
885         @NonNull
setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)886         public Builder setEncryptionPaddings(
887                 @KeyProperties.EncryptionPaddingEnum String... paddings) {
888             mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
889             return this;
890         }
891 
892         /**
893          * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
894          * can be used when signing/verifying. Attempts to use the key with any other padding scheme
895          * will be rejected.
896          *
897          * <p>This must be specified for RSA keys which are used for signing/verification.
898          *
899          * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
900          */
901         @NonNull
setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)902         public Builder setSignaturePaddings(
903                 @KeyProperties.SignaturePaddingEnum String... paddings) {
904             mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
905             return this;
906         }
907 
908         /**
909          * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
910          * used when encrypting/decrypting. Attempts to use the key with any other block modes will
911          * be rejected.
912          *
913          * <p>This must be specified for symmetric encryption/decryption keys.
914          *
915          * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
916          */
917         @NonNull
setBlockModes(@eyProperties.BlockModeEnum String... blockModes)918         public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
919             mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
920             return this;
921         }
922 
923         /**
924          * Sets whether encryption using this key must be sufficiently randomized to produce
925          * different ciphertexts for the same plaintext every time. The formal cryptographic
926          * property being required is <em>indistinguishability under chosen-plaintext attack
927          * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
928          * of weaknesses due to which ciphertext may leak information about plaintext. For example,
929          * if a given plaintext always produces the same ciphertext, an attacker may see the
930          * repeated ciphertexts and be able to deduce something about the plaintext.
931          *
932          * <p>By default, {@code IND-CPA} is required.
933          *
934          * <p>When {@code IND-CPA} is required:
935          * <ul>
936          * <li>encryption/decryption transformation which do not offer {@code IND-CPA}, such as
937          * {@code ECB} with a symmetric encryption algorithm, or RSA encryption/decryption without
938          * padding, are prohibited;</li>
939          * <li>in block modes which use an IV, such as {@code GCM}, {@code CBC}, and {@code CTR},
940          * caller-provided IVs are rejected when encrypting, to ensure that only random IVs are
941          * used.</li>
942          * </ul>
943          *
944          * <p>Before disabling this requirement, consider the following approaches instead:
945          * <ul>
946          * <li>If you are generating a random IV for encryption and then initializing a {@code}
947          * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
948          * instead. This will occur if the {@code Cipher} is initialized for encryption without an
949          * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
950          * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
951          * random, such as the name of the file being encrypted, or transaction ID, or password,
952          * or a device identifier), consider changing your design to use a random IV which will then
953          * be provided in addition to the ciphertext to the entities which need to decrypt the
954          * ciphertext.</li>
955          * <li>If you are using RSA encryption without padding, consider switching to encryption
956          * padding schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
957          * </ul>
958          */
959         @NonNull
setRandomizedEncryptionRequired(boolean required)960         public Builder setRandomizedEncryptionRequired(boolean required) {
961             mRandomizedEncryptionRequired = required;
962             return this;
963         }
964 
965         /**
966          * Sets whether this key is authorized to be used only if the user has been authenticated.
967          *
968          * <p>By default, the key is authorized to be used regardless of whether the user has been
969          * authenticated.
970          *
971          * <p>When user authentication is required:
972          * <ul>
973          * <li>The key can only be generated if secure lock screen is set up (see
974          * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
975          * authentication takes place for every use of the key (see
976          * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one fingerprint
977          * must be enrolled (see {@link FingerprintManager#hasEnrolledFingerprints()}).</li>
978          * <li>The use of the key must be authorized by the user by authenticating to this Android
979          * device using a subset of their secure lock screen credentials such as
980          * password/PIN/pattern or fingerprint.
981          * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
982          * information</a>.
983          * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
984          * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
985          * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
986          * Additionally, if the key requires that user authentication takes place for every use of
987          * the key, it is also irreversibly invalidated once a new fingerprint is enrolled or once\
988          * no more fingerprints are enrolled, unless {@link
989          * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
990          * enrollment. Attempts to initialize cryptographic operations using such keys will throw
991          * {@link KeyPermanentlyInvalidatedException}.</li>
992          * </ul>
993          *
994          * <p>This authorization applies only to secret key and private key operations. Public key
995          * operations are not restricted.
996          *
997          * @see #setUserAuthenticationValidityDurationSeconds(int)
998          * @see KeyguardManager#isDeviceSecure()
999          * @see FingerprintManager#hasEnrolledFingerprints()
1000          */
1001         @NonNull
setUserAuthenticationRequired(boolean required)1002         public Builder setUserAuthenticationRequired(boolean required) {
1003             mUserAuthenticationRequired = required;
1004             return this;
1005         }
1006 
1007         /**
1008          * Sets the duration of time (seconds) for which this key is authorized to be used after the
1009          * user is successfully authenticated. This has effect if the key requires user
1010          * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
1011          *
1012          * <p>By default, if user authentication is required, it must take place for every use of
1013          * the key.
1014          *
1015          * <p>Cryptographic operations involving keys which require user authentication to take
1016          * place for every operation can only use fingerprint authentication. This is achieved by
1017          * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
1018          * with the key, wrapping it into a {@link FingerprintManager.CryptoObject}, invoking
1019          * {@code FingerprintManager.authenticate} with {@code CryptoObject}, and proceeding with
1020          * the cryptographic operation only if the authentication flow succeeds.
1021          *
1022          * <p>Cryptographic operations involving keys which are authorized to be used for a duration
1023          * of time after a successful user authentication event can only use secure lock screen
1024          * authentication. These cryptographic operations will throw
1025          * {@link UserNotAuthenticatedException} during initialization if the user needs to be
1026          * authenticated to proceed. This situation can be resolved by the user unlocking the secure
1027          * lock screen of the Android or by going through the confirm credential flow initiated by
1028          * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
1029          * Once resolved, initializing a new cryptographic operation using this key (or any other
1030          * key which is authorized to be used for a fixed duration of time after user
1031          * authentication) should succeed provided the user authentication flow completed
1032          * successfully.
1033          *
1034          * @param seconds duration in seconds or {@code -1} if user authentication must take place
1035          *        for every use of the key.
1036          *
1037          * @see #setUserAuthenticationRequired(boolean)
1038          * @see FingerprintManager
1039          * @see FingerprintManager.CryptoObject
1040          * @see KeyguardManager
1041          */
1042         @NonNull
setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)1043         public Builder setUserAuthenticationValidityDurationSeconds(
1044                 @IntRange(from = -1) int seconds) {
1045             if (seconds < -1) {
1046                 throw new IllegalArgumentException("seconds must be -1 or larger");
1047             }
1048             mUserAuthenticationValidityDurationSeconds = seconds;
1049             return this;
1050         }
1051 
1052         /**
1053          * Sets whether an attestation certificate will be generated for this key pair, and what
1054          * challenge value will be placed in the certificate.  The attestation certificate chain
1055          * can be retrieved with with {@link java.security.KeyStore#getCertificateChain(String)}.
1056          *
1057          * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for
1058          * this key pair will contain an extension that describes the details of the key's
1059          * configuration and authorizations, including the {@code attestationChallenge} value. If
1060          * the key is in secure hardware, and if the secure hardware supports attestation, the
1061          * certificate will be signed by a chain of certificates rooted at a trustworthy CA key.
1062          * Otherwise the chain will be rooted at an untrusted certificate.
1063          *
1064          * <p>The purpose of the challenge value is to enable relying parties to verify that the key
1065          * was created in response to a specific request. If attestation is desired but no
1066          * challenged is needed, any non-{@code null} value may be used, including an empty byte
1067          * array.
1068          *
1069          * <p>If {@code attestationChallenge} is {@code null}, and this spec is used to generate an
1070          * asymmetric (RSA or EC) key pair, the public key certificate will be self-signed if the
1071          * key has purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}. If the key
1072          * does not have purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}, it is
1073          * not possible to use the key to sign a certificate, so the public key certificate will
1074          * contain a dummy signature.
1075          *
1076          * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
1077          * {@link #getAttestationChallenge()} returns non-null and the spec is used to generate a
1078          * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
1079          * {@link java.security.InvalidAlgorithmParameterException}.
1080          */
1081         @NonNull
setAttestationChallenge(byte[] attestationChallenge)1082         public Builder setAttestationChallenge(byte[] attestationChallenge) {
1083             mAttestationChallenge = attestationChallenge;
1084             return this;
1085         }
1086 
1087         /**
1088          * @hide Only system apps can use this method.
1089          *
1090          * Sets whether to include a temporary unique ID field in the attestation certificate.
1091          */
1092         @NonNull
setUniqueIdIncluded(boolean uniqueIdIncluded)1093         public Builder setUniqueIdIncluded(boolean uniqueIdIncluded) {
1094             mUniqueIdIncluded = uniqueIdIncluded;
1095             return this;
1096         }
1097 
1098         /**
1099          * Sets whether the key will remain authorized only until the device is removed from the
1100          * user's body up to the limit of the authentication validity period (see
1101          * {@link #setUserAuthenticationValidityDurationSeconds} and
1102          * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
1103          * user's body, the key will be considered unauthorized and the user will need to
1104          * re-authenticate to use it. For keys without an authentication validity period this
1105          * parameter has no effect.
1106          *
1107          * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
1108          * effect; the device will always be considered to be "on-body" and the key will therefore
1109          * remain authorized until the validity period ends.
1110          *
1111          * @param remainsValid if {@code true}, and if the device supports on-body detection, key
1112          * will be invalidated when the device is removed from the user's body or when the
1113          * authentication validity expires, whichever occurs first.
1114          */
1115         @NonNull
setUserAuthenticationValidWhileOnBody(boolean remainsValid)1116         public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
1117             mUserAuthenticationValidWhileOnBody = remainsValid;
1118             return this;
1119         }
1120 
1121         /**
1122          * Sets whether this key should be invalidated on fingerprint enrollment.  This
1123          * applies only to keys which require user authentication (see {@link
1124          * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
1125          * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
1126          * valid for fingerprint authentication only.
1127          *
1128          * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
1129          * fingerprint authentication only are <em>irreversibly invalidated</em> when a new
1130          * fingerprint is enrolled, or when all existing fingerprints are deleted.  That may be
1131          * changed by calling this method with {@code invalidateKey} set to {@code false}.
1132          *
1133          * <p>Invalidating keys on enrollment of a new finger or unenrollment of all fingers
1134          * improves security by ensuring that an unauthorized person who obtains the password can't
1135          * gain the use of fingerprint-authenticated keys by enrolling their own finger.  However,
1136          * invalidating keys makes key-dependent operations impossible, requiring some fallback
1137          * procedure to authenticate the user and set up a new key.
1138          */
1139         @NonNull
setInvalidatedByBiometricEnrollment(boolean invalidateKey)1140         public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
1141             mInvalidatedByBiometricEnrollment = invalidateKey;
1142             return this;
1143         }
1144 
1145         /**
1146          * Builds an instance of {@code KeyGenParameterSpec}.
1147          */
1148         @NonNull
build()1149         public KeyGenParameterSpec build() {
1150             return new KeyGenParameterSpec(
1151                     mKeystoreAlias,
1152                     mUid,
1153                     mKeySize,
1154                     mSpec,
1155                     mCertificateSubject,
1156                     mCertificateSerialNumber,
1157                     mCertificateNotBefore,
1158                     mCertificateNotAfter,
1159                     mKeyValidityStart,
1160                     mKeyValidityForOriginationEnd,
1161                     mKeyValidityForConsumptionEnd,
1162                     mPurposes,
1163                     mDigests,
1164                     mEncryptionPaddings,
1165                     mSignaturePaddings,
1166                     mBlockModes,
1167                     mRandomizedEncryptionRequired,
1168                     mUserAuthenticationRequired,
1169                     mUserAuthenticationValidityDurationSeconds,
1170                     mAttestationChallenge,
1171                     mUniqueIdIncluded,
1172                     mUserAuthenticationValidWhileOnBody,
1173                     mInvalidatedByBiometricEnrollment);
1174         }
1175     }
1176 }
1177