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