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