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.SystemApi;
23 import android.annotation.TestApi;
24 import android.app.KeyguardManager;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.hardware.biometrics.BiometricManager;
27 import android.hardware.biometrics.BiometricPrompt;
28 import android.os.Build;
29 import android.security.GateKeeper;
30 import android.text.TextUtils;
31 
32 import java.math.BigInteger;
33 import java.security.KeyPairGenerator;
34 import java.security.Signature;
35 import java.security.cert.Certificate;
36 import java.security.spec.AlgorithmParameterSpec;
37 import java.util.Date;
38 
39 import javax.crypto.Cipher;
40 import javax.crypto.KeyGenerator;
41 import javax.crypto.Mac;
42 import javax.security.auth.x500.X500Principal;
43 
44 /**
45  * {@link AlgorithmParameterSpec} for initializing a {@link KeyPairGenerator} or a
46  * {@link KeyGenerator} of the <a href="{@docRoot}training/articles/keystore.html">Android Keystore
47  * system</a>. The spec determines authorized uses of the key, such as whether user authentication
48  * is required for using the key, what operations are authorized (e.g., signing, but not
49  * decryption), with what parameters (e.g., only with a particular padding scheme or digest), and
50  * the key's validity start and end dates. Key use authorizations expressed in the spec apply
51  * only to secret keys and private keys -- public keys can be used for any supported operations.
52  *
53  * <p>To generate an asymmetric key pair or a symmetric key, create an instance of this class using
54  * the {@link Builder}, initialize a {@code KeyPairGenerator} or a {@code KeyGenerator} of the
55  * desired key type (e.g., {@code EC} or {@code AES} -- see
56  * {@link KeyProperties}.{@code KEY_ALGORITHM} constants) from the {@code AndroidKeyStore} provider
57  * with the {@code KeyGenParameterSpec} instance, and then generate a key or key pair using
58  * {@link KeyGenerator#generateKey()} or {@link KeyPairGenerator#generateKeyPair()}.
59  *
60  * <p>The generated key pair or key will be returned by the generator and also stored in the Android
61  * Keystore under the alias specified in this spec. To obtain the secret or private key from the
62  * Android Keystore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)}
63  * or {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
64  * To obtain the public key from the Android Keystore use
65  * {@link java.security.KeyStore#getCertificate(String)} and then
66  * {@link Certificate#getPublicKey()}.
67  *
68  * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
69  * Keystore, generated private keys implement {@link java.security.interfaces.ECKey} or
70  * {@link java.security.interfaces.RSAKey} interfaces whereas public keys implement
71  * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
72  * interfaces.
73  *
74  * <p>For asymmetric key pairs, a self-signed X.509 certificate will be also generated and stored in
75  * the Android Keystore. This is because the {@link java.security.KeyStore} abstraction does not
76  * support storing key pairs without a certificate. The subject, serial number, and validity dates
77  * of the certificate can be customized in this spec. The self-signed certificate may be replaced at
78  * a later time by a certificate signed by a Certificate Authority (CA).
79  *
80  * <p>NOTE: If a private key is not authorized to sign the self-signed certificate, then the
81  * certificate will be created with an invalid signature which will not verify. Such a certificate
82  * is still useful because it provides access to the public key. To generate a valid signature for
83  * the certificate the key needs to be authorized for all of the following:
84  * <ul>
85  * <li>{@link KeyProperties#PURPOSE_SIGN},</li>
86  * <li>operation without requiring the user to be authenticated (see
87  * {@link Builder#setUserAuthenticationRequired(boolean)}),</li>
88  * <li>signing/origination at this moment in time (see {@link Builder#setKeyValidityStart(Date)}
89  * and {@link Builder#setKeyValidityForOriginationEnd(Date)}),</li>
90  * <li>suitable digest,</li>
91  * <li>(RSA keys only) padding scheme {@link KeyProperties#SIGNATURE_PADDING_RSA_PKCS1}.</li>
92  * </ul>
93  *
94  * <p>NOTE: The key material of the generated symmetric and private keys is not accessible. The key
95  * material of the public keys is accessible.
96  *
97  * <p>Instances of this class are immutable.
98  *
99  * <p><h3>Known issues</h3>
100  * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be
101  * enforced even for public keys. To work around this issue extract the public key material to use
102  * outside of Android Keystore. For example:
103  * <pre> {@code
104  * PublicKey unrestrictedPublicKey =
105  *         KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
106  *                 new X509EncodedKeySpec(publicKey.getEncoded()));
107  * }</pre>
108  *
109  * <p><h3>Example: NIST P-256 EC key pair for signing/verification using ECDSA</h3>
110  * This example illustrates how to generate a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair
111  * in the Android KeyStore system under alias {@code key1} where the private key is authorized to be
112  * used only for signing using SHA-256, SHA-384, or SHA-512 digest and only if the user has been
113  * authenticated within the last five minutes. The use of the public key is unrestricted (See Known
114  * Issues).
115  * <pre> {@code
116  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
117  *         KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
118  * keyPairGenerator.initialize(
119  *         new KeyGenParameterSpec.Builder(
120  *                 "key1",
121  *                 KeyProperties.PURPOSE_SIGN)
122  *                 .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
123  *                 .setDigests(KeyProperties.DIGEST_SHA256,
124  *                         KeyProperties.DIGEST_SHA384,
125  *                         KeyProperties.DIGEST_SHA512)
126  *                 // Only permit the private key to be used if the user authenticated
127  *                 // within the last five minutes.
128  *                 .setUserAuthenticationRequired(true)
129  *                 .setUserAuthenticationValidityDurationSeconds(5 * 60)
130  *                 .build());
131  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
132  * Signature signature = Signature.getInstance("SHA256withECDSA");
133  * signature.initSign(keyPair.getPrivate());
134  * ...
135  *
136  * // The key pair can also be obtained from the Android Keystore any time as follows:
137  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
138  * keyStore.load(null);
139  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
140  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
141  * }</pre>
142  *
143  * <p><h3>Example: RSA key pair for signing/verification using RSA-PSS</h3>
144  * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
145  * alias {@code key1} authorized to be used only for signing using the RSA-PSS signature padding
146  * scheme with SHA-256 or SHA-512 digests. The use of the public key is unrestricted.
147  * <pre> {@code
148  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
149  *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
150  * keyPairGenerator.initialize(
151  *         new KeyGenParameterSpec.Builder(
152  *                 "key1",
153  *                 KeyProperties.PURPOSE_SIGN)
154  *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
155  *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
156  *                 .build());
157  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
158  * Signature signature = Signature.getInstance("SHA256withRSA/PSS");
159  * signature.initSign(keyPair.getPrivate());
160  * ...
161  *
162  * // The key pair can also be obtained from the Android Keystore any time as follows:
163  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
164  * keyStore.load(null);
165  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
166  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
167  * }</pre>
168  *
169  * <p><h3>Example: RSA key pair for encryption/decryption using RSA OAEP</h3>
170  * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
171  * alias {@code key1} where the private key is authorized to be used only for decryption using RSA
172  * OAEP encryption padding scheme with SHA-256 or SHA-512 digests. The use of the public key is
173  * unrestricted.
174  * <pre> {@code
175  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
176  *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
177  * keyPairGenerator.initialize(
178  *         new KeyGenParameterSpec.Builder(
179  *                 "key1",
180  *                 KeyProperties.PURPOSE_DECRYPT)
181  *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
182  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
183  *                 .build());
184  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
185  * Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
186  * cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
187  * ...
188  *
189  * // The key pair can also be obtained from the Android Keystore any time as follows:
190  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
191  * keyStore.load(null);
192  * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
193  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
194  * }</pre>
195  *
196  * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
197  * The following example illustrates how to generate an AES key in the Android KeyStore system under
198  * alias {@code key2} authorized to be used only for encryption/decryption in GCM mode with no
199  * padding.
200  * <pre> {@code
201  * KeyGenerator keyGenerator = KeyGenerator.getInstance(
202  *         KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
203  * keyGenerator.init(
204  *         new KeyGenParameterSpec.Builder("key2",
205  *                 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
206  *                 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
207  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
208  *                 .build());
209  * SecretKey key = keyGenerator.generateKey();
210  *
211  * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
212  * cipher.init(Cipher.ENCRYPT_MODE, key);
213  * ...
214  *
215  * // The key can also be obtained from the Android Keystore any time as follows:
216  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
217  * keyStore.load(null);
218  * key = (SecretKey) keyStore.getKey("key2", null);
219  * }</pre>
220  *
221  * <p><h3>Example: HMAC key for generating a MAC using SHA-256</h3>
222  * This example illustrates how to generate an HMAC key in the Android KeyStore system under alias
223  * {@code key2} authorized to be used only for generating an HMAC using SHA-256.
224  * <pre> {@code
225  * KeyGenerator keyGenerator = KeyGenerator.getInstance(
226  *         KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
227  * keyGenerator.init(
228  *         new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build());
229  * SecretKey key = keyGenerator.generateKey();
230  * Mac mac = Mac.getInstance("HmacSHA256");
231  * mac.init(key);
232  * ...
233  *
234  * // The key can also be obtained from the Android Keystore any time as follows:
235  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
236  * keyStore.load(null);
237  * key = (SecretKey) keyStore.getKey("key2", null);
238  * }</pre>
239  *
240  * <p><h3 id="example:ecdh">Example: EC key for ECDH key agreement</h3>
241  * This example illustrates how to generate an elliptic curve key pair, used to establish a shared
242  * secret with another party using ECDH key agreement.
243  * <pre> {@code
244  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
245  *         KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
246  * keyPairGenerator.initialize(
247  *         new KeyGenParameterSpec.Builder(
248  *             "eckeypair",
249  *             KeyProperties.PURPOSE_AGREE_KEY)
250  *             .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
251  *             .build());
252  * KeyPair myKeyPair = keyPairGenerator.generateKeyPair();
253  *
254  * // Exchange public keys with server. A new ephemeral key MUST be used for every message.
255  * PublicKey serverEphemeralPublicKey; // Ephemeral key received from server.
256  *
257  * // Create a shared secret based on our private key and the other party's public key.
258  * KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "AndroidKeyStore");
259  * keyAgreement.init(myKeyPair.getPrivate());
260  * keyAgreement.doPhase(serverEphemeralPublicKey, true);
261  * byte[] sharedSecret = keyAgreement.generateSecret();
262  *
263  * // sharedSecret cannot safely be used as a key yet. We must run it through a key derivation
264  * // function with some other data: "salt" and "info". Salt is an optional random value,
265  * // omitted in this example. It's good practice to include both public keys and any other
266  * // key negotiation data in info. Here we use the public keys and a label that indicates
267  * // messages encrypted with this key are coming from the server.
268  * byte[] salt = {};
269  * ByteArrayOutputStream info = new ByteArrayOutputStream();
270  * info.write("ECDH secp256r1 AES-256-GCM-SIV\0".getBytes(StandardCharsets.UTF_8));
271  * info.write(myKeyPair.getPublic().getEncoded());
272  * info.write(serverEphemeralPublicKey.getEncoded());
273  *
274  * // This example uses the Tink library and the HKDF key derivation function.
275  * AesGcmSiv key = new AesGcmSiv(Hkdf.computeHkdf(
276  *         "HMACSHA256", sharedSecret, salt, info.toByteArray(), 32));
277  * byte[] associatedData = {};
278  * return key.decrypt(ciphertext, associatedData);
279  * }</pre>
280  */
281 public final class KeyGenParameterSpec implements AlgorithmParameterSpec, UserAuthArgs {
282     private static final X500Principal DEFAULT_ATTESTATION_CERT_SUBJECT =
283             new X500Principal("CN=Android Keystore Key");
284     private static final X500Principal DEFAULT_SELF_SIGNED_CERT_SUBJECT =
285             new X500Principal("CN=Fake");
286     private static final BigInteger DEFAULT_CERT_SERIAL_NUMBER = new BigInteger("1");
287     private static final Date DEFAULT_CERT_NOT_BEFORE = new Date(0L); // Jan 1 1970
288     private static final Date DEFAULT_CERT_NOT_AFTER = new Date(2461449600000L); // Jan 1 2048
289 
290     private final String mKeystoreAlias;
291     private final @KeyProperties.Namespace int mNamespace;
292     private final int mKeySize;
293     private final AlgorithmParameterSpec mSpec;
294     private final X500Principal mCertificateSubject;
295     private final BigInteger mCertificateSerialNumber;
296     private final Date mCertificateNotBefore;
297     private final Date mCertificateNotAfter;
298     private final Date mKeyValidityStart;
299     private final Date mKeyValidityForOriginationEnd;
300     private final Date mKeyValidityForConsumptionEnd;
301     private final @KeyProperties.PurposeEnum int mPurposes;
302     private final @KeyProperties.DigestEnum String[] mDigests;
303     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
304     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
305     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
306     private final boolean mRandomizedEncryptionRequired;
307     private final boolean mUserAuthenticationRequired;
308     private final int mUserAuthenticationValidityDurationSeconds;
309     private final @KeyProperties.AuthEnum int mUserAuthenticationType;
310     private final boolean mUserPresenceRequired;
311     private final byte[] mAttestationChallenge;
312     private final boolean mDevicePropertiesAttestationIncluded;
313     private final int[] mAttestationIds;
314     private final boolean mUniqueIdIncluded;
315     private final boolean mUserAuthenticationValidWhileOnBody;
316     private final boolean mInvalidatedByBiometricEnrollment;
317     private final boolean mIsStrongBoxBacked;
318     private final boolean mUserConfirmationRequired;
319     private final boolean mUnlockedDeviceRequired;
320     private final boolean mCriticalToDeviceEncryption;
321     private final int mMaxUsageCount;
322     private final String mAttestKeyAlias;
323     private final long mBoundToSecureUserId;
324 
325     /*
326      * ***NOTE***: All new fields MUST also be added to the following:
327      * ParcelableKeyGenParameterSpec class.
328      * The KeyGenParameterSpec.Builder constructor that takes a KeyGenParameterSpec
329      */
330 
331     /**
332      * @hide should be built with Builder
333      */
KeyGenParameterSpec( String keyStoreAlias, @KeyProperties.Namespace int namespace, 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, @KeyProperties.AuthEnum int userAuthenticationType, boolean userPresenceRequired, byte[] attestationChallenge, boolean devicePropertiesAttestationIncluded, @NonNull int[] attestationIds, boolean uniqueIdIncluded, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment, boolean isStrongBoxBacked, boolean userConfirmationRequired, boolean unlockedDeviceRequired, boolean criticalToDeviceEncryption, int maxUsageCount, String attestKeyAlias, long boundToSecureUserId)334     public KeyGenParameterSpec(
335             String keyStoreAlias,
336             @KeyProperties.Namespace int namespace,
337             int keySize,
338             AlgorithmParameterSpec spec,
339             X500Principal certificateSubject,
340             BigInteger certificateSerialNumber,
341             Date certificateNotBefore,
342             Date certificateNotAfter,
343             Date keyValidityStart,
344             Date keyValidityForOriginationEnd,
345             Date keyValidityForConsumptionEnd,
346             @KeyProperties.PurposeEnum int purposes,
347             @KeyProperties.DigestEnum String[] digests,
348             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
349             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
350             @KeyProperties.BlockModeEnum String[] blockModes,
351             boolean randomizedEncryptionRequired,
352             boolean userAuthenticationRequired,
353             int userAuthenticationValidityDurationSeconds,
354             @KeyProperties.AuthEnum int userAuthenticationType,
355             boolean userPresenceRequired,
356             byte[] attestationChallenge,
357             boolean devicePropertiesAttestationIncluded,
358             @NonNull int[] attestationIds,
359             boolean uniqueIdIncluded,
360             boolean userAuthenticationValidWhileOnBody,
361             boolean invalidatedByBiometricEnrollment,
362             boolean isStrongBoxBacked,
363             boolean userConfirmationRequired,
364             boolean unlockedDeviceRequired,
365             boolean criticalToDeviceEncryption,
366             int maxUsageCount,
367             String attestKeyAlias,
368             long boundToSecureUserId) {
369         if (TextUtils.isEmpty(keyStoreAlias)) {
370             throw new IllegalArgumentException("keyStoreAlias must not be empty");
371         }
372 
373         if (certificateSubject == null) {
374             if (attestationChallenge == null) {
375                 certificateSubject = DEFAULT_SELF_SIGNED_CERT_SUBJECT;
376             } else {
377                 certificateSubject = DEFAULT_ATTESTATION_CERT_SUBJECT;
378             }
379         }
380         if (certificateNotBefore == null) {
381             certificateNotBefore = DEFAULT_CERT_NOT_BEFORE;
382         }
383         if (certificateNotAfter == null) {
384             certificateNotAfter = DEFAULT_CERT_NOT_AFTER;
385         }
386         if (certificateSerialNumber == null) {
387             certificateSerialNumber = DEFAULT_CERT_SERIAL_NUMBER;
388         }
389 
390         if (certificateNotAfter.before(certificateNotBefore)) {
391             throw new IllegalArgumentException("certificateNotAfter < certificateNotBefore");
392         }
393 
394         mKeystoreAlias = keyStoreAlias;
395         mNamespace = namespace;
396         mKeySize = keySize;
397         mSpec = spec;
398         mCertificateSubject = certificateSubject;
399         mCertificateSerialNumber = certificateSerialNumber;
400         mCertificateNotBefore = Utils.cloneIfNotNull(certificateNotBefore);
401         mCertificateNotAfter = Utils.cloneIfNotNull(certificateNotAfter);
402         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
403         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
404         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
405         mPurposes = purposes;
406         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
407         mEncryptionPaddings =
408                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
409         mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
410         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
411         mRandomizedEncryptionRequired = randomizedEncryptionRequired;
412         mUserAuthenticationRequired = userAuthenticationRequired;
413         mUserPresenceRequired = userPresenceRequired;
414         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
415         mUserAuthenticationType = userAuthenticationType;
416         mAttestationChallenge = Utils.cloneIfNotNull(attestationChallenge);
417         mDevicePropertiesAttestationIncluded = devicePropertiesAttestationIncluded;
418         mAttestationIds = attestationIds;
419         mUniqueIdIncluded = uniqueIdIncluded;
420         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
421         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
422         mIsStrongBoxBacked = isStrongBoxBacked;
423         mUserConfirmationRequired = userConfirmationRequired;
424         mUnlockedDeviceRequired = unlockedDeviceRequired;
425         mCriticalToDeviceEncryption = criticalToDeviceEncryption;
426         mMaxUsageCount = maxUsageCount;
427         mAttestKeyAlias = attestKeyAlias;
428         mBoundToSecureUserId = boundToSecureUserId;
429     }
430 
431     /**
432      * Returns the alias that will be used in the {@code java.security.KeyStore}
433      * in conjunction with the {@code AndroidKeyStore}.
434      */
435     @NonNull
getKeystoreAlias()436     public String getKeystoreAlias() {
437         return mKeystoreAlias;
438     }
439 
440     /**
441      * Returns the UID which will own the key. {@code -1} is an alias for the UID of the current
442      * process.
443      *
444      * @deprecated See deprecation message on {@link KeyGenParameterSpec.Builder#setUid(int)}.
445      *             Known namespaces will be translated to their legacy UIDs. Unknown
446      *             Namespaces will yield {@link IllegalStateException}.
447      *
448      * @hide
449      */
450     @UnsupportedAppUsage
451     @Deprecated
getUid()452     public int getUid() {
453         try {
454             return KeyProperties.namespaceToLegacyUid(mNamespace);
455         } catch (IllegalArgumentException e) {
456             throw new IllegalStateException("getUid called on KeyGenParameterSpec with non legacy"
457                     + " keystore namespace.", e);
458         }
459     }
460 
461     /**
462      * Returns the target namespace for the key.
463      * See {@link KeyGenParameterSpec.Builder#setNamespace(int)}.
464      *
465      * @return The numeric namespace as configured in the keystore2_key_contexts files of Android's
466      *         SEPolicy.
467      *         See <a href="https://source.android.com/security/keystore#access-control">
468      *             Keystore 2.0 access control</a>
469      * @hide
470      */
471     @SystemApi
getNamespace()472     public @KeyProperties.Namespace int getNamespace() {
473         return mNamespace;
474     }
475 
476     /**
477      * Returns the requested key size. If {@code -1}, the size should be looked up from
478      * {@link #getAlgorithmParameterSpec()}, if provided, otherwise an algorithm-specific default
479      * size should be used.
480      */
getKeySize()481     public int getKeySize() {
482         return mKeySize;
483     }
484 
485     /**
486      * Returns the key algorithm-specific {@link AlgorithmParameterSpec} that will be used for
487      * creation of the key or {@code null} if algorithm-specific defaults should be used.
488      */
489     @Nullable
getAlgorithmParameterSpec()490     public AlgorithmParameterSpec getAlgorithmParameterSpec() {
491         return mSpec;
492     }
493 
494     /**
495      * Returns the subject distinguished name to be used on the X.509 certificate that will be put
496      * in the {@link java.security.KeyStore}.
497      */
498     @NonNull
getCertificateSubject()499     public X500Principal getCertificateSubject() {
500         return mCertificateSubject;
501     }
502 
503     /**
504      * Returns the serial number to be used on the X.509 certificate that will be put in the
505      * {@link java.security.KeyStore}.
506      */
507     @NonNull
getCertificateSerialNumber()508     public BigInteger getCertificateSerialNumber() {
509         return mCertificateSerialNumber;
510     }
511 
512     /**
513      * Returns the start date to be used on the X.509 certificate that will be put in the
514      * {@link java.security.KeyStore}.
515      */
516     @NonNull
getCertificateNotBefore()517     public Date getCertificateNotBefore() {
518         return Utils.cloneIfNotNull(mCertificateNotBefore);
519     }
520 
521     /**
522      * Returns the end date to be used on the X.509 certificate that will be put in the
523      * {@link java.security.KeyStore}.
524      */
525     @NonNull
getCertificateNotAfter()526     public Date getCertificateNotAfter() {
527         return Utils.cloneIfNotNull(mCertificateNotAfter);
528     }
529 
530     /**
531      * Returns the time instant before which the key is not yet valid or {@code null} if not
532      * restricted.
533      */
534     @Nullable
getKeyValidityStart()535     public Date getKeyValidityStart() {
536         return Utils.cloneIfNotNull(mKeyValidityStart);
537     }
538 
539     /**
540      * Returns the time instant after which the key is no longer valid for decryption and
541      * verification or {@code null} if not restricted.
542      */
543     @Nullable
getKeyValidityForConsumptionEnd()544     public Date getKeyValidityForConsumptionEnd() {
545         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
546     }
547 
548     /**
549      * Returns the time instant after which the key is no longer valid for encryption and signing
550      * or {@code null} if not restricted.
551      */
552     @Nullable
getKeyValidityForOriginationEnd()553     public Date getKeyValidityForOriginationEnd() {
554         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
555     }
556 
557     /**
558      * Returns the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
559      * Attempts to use the key for any other purpose will be rejected.
560      *
561      * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
562      */
getPurposes()563     public @KeyProperties.PurposeEnum int getPurposes() {
564         return mPurposes;
565     }
566 
567     /**
568      * Returns the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384} with which the
569      * key can be used or {@code null} if not specified.
570      *
571      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
572      *
573      * @throws IllegalStateException if this set has not been specified.
574      *
575      * @see #isDigestsSpecified()
576      */
577     @NonNull
getDigests()578     public @KeyProperties.DigestEnum String[] getDigests() {
579         if (mDigests == null) {
580             throw new IllegalStateException("Digests not specified");
581         }
582         return ArrayUtils.cloneIfNotEmpty(mDigests);
583     }
584 
585     /**
586      * Returns {@code true} if the set of digest algorithms with which the key can be used has been
587      * specified.
588      *
589      * @see #getDigests()
590      */
591     @NonNull
isDigestsSpecified()592     public boolean isDigestsSpecified() {
593         return mDigests != null;
594     }
595 
596     /**
597      * Returns the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OEAPPadding},
598      * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
599      * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
600      * rejected.
601      *
602      * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
603      */
604     @NonNull
getEncryptionPaddings()605     public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
606         return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
607     }
608 
609     /**
610      * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
611      * can be used when signing/verifying. Attempts to use the key with any other padding scheme
612      * will be rejected.
613      *
614      * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
615      */
616     @NonNull
getSignaturePaddings()617     public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
618         return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
619     }
620 
621     /**
622      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
623      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
624      * rejected.
625      *
626      * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
627      */
628     @NonNull
getBlockModes()629     public @KeyProperties.BlockModeEnum String[] getBlockModes() {
630         return ArrayUtils.cloneIfNotEmpty(mBlockModes);
631     }
632 
633     /**
634      * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
635      * different ciphertexts for the same plaintext every time. The formal cryptographic property
636      * being required is <em>indistinguishability under chosen-plaintext attack ({@code
637      * IND-CPA})</em>. This property is important because it mitigates several classes of
638      * weaknesses due to which ciphertext may leak information about plaintext.  For example, if a
639      * given plaintext always produces the same ciphertext, an attacker may see the repeated
640      * ciphertexts and be able to deduce something about the plaintext.
641      */
isRandomizedEncryptionRequired()642     public boolean isRandomizedEncryptionRequired() {
643         return mRandomizedEncryptionRequired;
644     }
645 
646     /**
647      * Returns {@code true} if the key is authorized to be used only if the user has been
648      * authenticated.
649      *
650      * <p>This authorization applies only to secret key and private key operations. Public key
651      * operations are not restricted.
652      *
653      * @see #getUserAuthenticationValidityDurationSeconds()
654      * @see Builder#setUserAuthenticationRequired(boolean)
655      */
isUserAuthenticationRequired()656     public boolean isUserAuthenticationRequired() {
657         return mUserAuthenticationRequired;
658     }
659 
660     /**
661      * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
662      * user.
663      *
664      * Confirmation is separate from user authentication (see
665      * {@link Builder#setUserAuthenticationRequired(boolean)}). Keys can be created that require
666      * confirmation but not user authentication, or user authentication but not confirmation, or
667      * both. Confirmation verifies that some user with physical possession of the device has
668      * approved a displayed message. User authentication verifies that the correct user is present
669      * and has authenticated.
670      *
671      * <p>This authorization applies only to secret key and private key operations. Public key
672      * operations are not restricted.
673      *
674      * @see Builder#setUserConfirmationRequired(boolean)
675      */
isUserConfirmationRequired()676     public boolean isUserConfirmationRequired() {
677         return mUserConfirmationRequired;
678     }
679 
680     /**
681      * Gets the duration of time (seconds) for which this key is authorized to be used after the
682      * user is successfully authenticated. This has effect only if user authentication is required
683      * (see {@link #isUserAuthenticationRequired()}).
684      *
685      * <p>This authorization applies only to secret key and private key operations. Public key
686      * operations are not restricted.
687      *
688      * @return duration in seconds or {@code -1} if authentication is required for every use of the
689      *         key.
690      *
691      * @see #isUserAuthenticationRequired()
692      * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
693      */
getUserAuthenticationValidityDurationSeconds()694     public int getUserAuthenticationValidityDurationSeconds() {
695         return mUserAuthenticationValidityDurationSeconds;
696     }
697 
698     /**
699      * Gets the modes of authentication that can authorize use of this key. This has effect only if
700      * user authentication is required (see {@link #isUserAuthenticationRequired()}).
701      *
702      * <p>This authorization applies only to secret key and private key operations. Public key
703      * operations are not restricted.
704      *
705      * @return integer representing the bitwse OR of all acceptable authentication types for the
706      *         key.
707      *
708      * @see #isUserAuthenticationRequired()
709      * @see Builder#setUserAuthenticationParameters(int, int)
710      */
getUserAuthenticationType()711     public @KeyProperties.AuthEnum int getUserAuthenticationType() {
712         return mUserAuthenticationType;
713     }
714     /**
715      * Returns {@code true} if the key is authorized to be used only if a test of user presence has
716      * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls.
717      * It requires that the KeyStore implementation have a direct way to validate the user presence
718      * for example a KeyStore hardware backed strongbox can use a button press that is observable
719      * in hardware. A test for user presence is tangential to authentication. The test can be part
720      * of an authentication step as long as this step can be validated by the hardware protecting
721      * the key and cannot be spoofed. For example, a physical button press can be used as a test of
722      * user presence if the other pins connected to the button are not able to simulate a button
723      * press. There must be no way for the primary processor to fake a button press, or that
724      * button must not be used as a test of user presence.
725      */
isUserPresenceRequired()726     public boolean isUserPresenceRequired() {
727         return mUserPresenceRequired;
728     }
729 
730     /**
731      * Returns the attestation challenge value that will be placed in attestation certificate for
732      * this key pair.
733      *
734      * <p>If this method returns non-{@code null}, the public key certificate for this key pair will
735      * contain an extension that describes the details of the key's configuration and
736      * authorizations, including the content of the attestation challenge value. If the key is in
737      * secure hardware, and if the secure hardware supports attestation, the certificate will be
738      * signed by a chain of certificates rooted at a trustworthy CA key. Otherwise the chain will
739      * be rooted at an untrusted certificate.
740      *
741      * <p>If this method returns {@code null}, and the spec is used to generate an asymmetric (RSA
742      * or EC) key pair, the public key will have a self-signed certificate if it has purpose {@link
743      * KeyProperties#PURPOSE_SIGN}. If does not have purpose {@link KeyProperties#PURPOSE_SIGN}, it
744      * will have a fake certificate.
745      *
746      * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
747      * KeyGenParameterSpec with getAttestationChallenge returning non-null is used to generate a
748      * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
749      * {@link java.security.InvalidAlgorithmParameterException}.
750      *
751      * @see Builder#setAttestationChallenge(byte[])
752      */
getAttestationChallenge()753     public byte[] getAttestationChallenge() {
754         return Utils.cloneIfNotNull(mAttestationChallenge);
755     }
756 
757     /**
758      * Returns {@code true} if attestation for the base device properties ({@link Build#BRAND},
759      * {@link Build#DEVICE}, {@link Build#MANUFACTURER}, {@link Build#MODEL}, {@link Build#PRODUCT})
760      * was requested to be added in the attestation certificate for the generated key.
761      *
762      * {@link javax.crypto.KeyGenerator#generateKey()} will throw
763      * {@link java.security.ProviderException} if device properties attestation fails or is not
764      * supported.
765      *
766      * @see Builder#setDevicePropertiesAttestationIncluded(boolean)
767      */
isDevicePropertiesAttestationIncluded()768     public boolean isDevicePropertiesAttestationIncluded() {
769         return mDevicePropertiesAttestationIncluded;
770     }
771 
772     /**
773      * @hide
774      * Allows the caller to specify device IDs to be attested to in the certificate for the
775      * generated key pair. These values are the enums specified in
776      * {@link android.security.keystore.AttestationUtils}
777      *
778      * @see android.security.keystore.AttestationUtils#ID_TYPE_SERIAL
779      * @see android.security.keystore.AttestationUtils#ID_TYPE_IMEI
780      * @see android.security.keystore.AttestationUtils#ID_TYPE_MEID
781      * @see android.security.keystore.AttestationUtils#USE_INDIVIDUAL_ATTESTATION
782      *
783      * @return integer array representing the requested device IDs to attest.
784      */
785     @SystemApi
getAttestationIds()786     public @NonNull int[] getAttestationIds() {
787         return mAttestationIds.clone();
788     }
789 
790     /**
791      * @hide This is a system-only API
792      *
793      * Returns {@code true} if the attestation certificate will contain a unique ID field.
794      */
795     @UnsupportedAppUsage
isUniqueIdIncluded()796     public boolean isUniqueIdIncluded() {
797         return mUniqueIdIncluded;
798     }
799 
800     /**
801      * Returns {@code true} if the key will remain authorized only until the device is removed from
802      * the user's body, up to the validity duration.  This option has no effect on keys that don't
803      * have an authentication validity duration, and has no effect if the device lacks an on-body
804      * sensor.
805      *
806      * <p>Authorization applies only to secret key and private key operations. Public key operations
807      * are not restricted.
808      *
809      * @see #isUserAuthenticationRequired()
810      * @see #getUserAuthenticationValidityDurationSeconds()
811      * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
812      */
isUserAuthenticationValidWhileOnBody()813     public boolean isUserAuthenticationValidWhileOnBody() {
814         return mUserAuthenticationValidWhileOnBody;
815     }
816 
817     /**
818      * Returns {@code true} if the key is irreversibly invalidated when a new biometric is
819      * enrolled or all enrolled biometrics are removed. This has effect only for keys that
820      * require biometric user authentication for every use.
821      *
822      * @see #isUserAuthenticationRequired()
823      * @see #getUserAuthenticationValidityDurationSeconds()
824      * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
825      */
isInvalidatedByBiometricEnrollment()826     public boolean isInvalidatedByBiometricEnrollment() {
827         return mInvalidatedByBiometricEnrollment;
828     }
829 
830     /**
831      * Returns {@code true} if the key is protected by a Strongbox security chip.
832      */
isStrongBoxBacked()833     public boolean isStrongBoxBacked() {
834         return mIsStrongBoxBacked;
835     }
836 
837     /**
838      * Returns {@code true} if the screen must be unlocked for this key to be used for decryption or
839      * signing. Encryption and signature verification will still be available when the screen is
840      * locked.
841      *
842      * @see Builder#setUnlockedDeviceRequired(boolean)
843      */
isUnlockedDeviceRequired()844     public boolean isUnlockedDeviceRequired() {
845         return mUnlockedDeviceRequired;
846     }
847 
848     /**
849      * Return the secure user id that this key should be bound to.
850      *
851      * Normally an authentication-bound key is tied to the secure user id of the current user
852      * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the authenticator
853      * id of the current biometric set for keys requiring explicit biometric authorization).
854      * If this parameter is set (this method returning non-zero value), the key should be tied to
855      * the specified secure user id, overriding the logic above.
856      *
857      * This is only applicable when {@link #isUserAuthenticationRequired} is {@code true}
858      *
859      * @hide
860      */
getBoundToSpecificSecureUserId()861     public long getBoundToSpecificSecureUserId() {
862         return mBoundToSecureUserId;
863     }
864 
865     /**
866      * Returns whether this key is critical to the device encryption flow.
867      *
868      * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
869      * @hide
870      */
isCriticalToDeviceEncryption()871     public boolean isCriticalToDeviceEncryption() {
872         return mCriticalToDeviceEncryption;
873     }
874 
875     /**
876      * Returns the maximum number of times the limited use key is allowed to be used or
877      * {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there’s no restriction on the number of
878      * times the key can be used.
879      *
880      * @see Builder#setMaxUsageCount(int)
881      */
getMaxUsageCount()882     public int getMaxUsageCount() {
883         return mMaxUsageCount;
884     }
885 
886     /**
887      * Returns the alias of the attestation key that will be used to sign the attestation
888      * certificate of the generated key.  Note that an attestation certificate will only be
889      * generated if an attestation challenge is set.
890      *
891      * @see Builder#setAttestKeyAlias(String)
892      */
893     @Nullable
getAttestKeyAlias()894     public String getAttestKeyAlias() {
895         return mAttestKeyAlias;
896     }
897 
898     /**
899      * Builder of {@link KeyGenParameterSpec} instances.
900      */
901     public final static class Builder {
902         private final String mKeystoreAlias;
903         private @KeyProperties.PurposeEnum int mPurposes;
904 
905         private @KeyProperties.Namespace int mNamespace = KeyProperties.NAMESPACE_APPLICATION;
906         private int mKeySize = -1;
907         private AlgorithmParameterSpec mSpec;
908         private X500Principal mCertificateSubject;
909         private BigInteger mCertificateSerialNumber;
910         private Date mCertificateNotBefore;
911         private Date mCertificateNotAfter;
912         private Date mKeyValidityStart;
913         private Date mKeyValidityForOriginationEnd;
914         private Date mKeyValidityForConsumptionEnd;
915         private @KeyProperties.DigestEnum String[] mDigests;
916         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
917         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
918         private @KeyProperties.BlockModeEnum String[] mBlockModes;
919         private boolean mRandomizedEncryptionRequired = true;
920         private boolean mUserAuthenticationRequired;
921         private int mUserAuthenticationValidityDurationSeconds = 0;
922         private @KeyProperties.AuthEnum int mUserAuthenticationType =
923                 KeyProperties.AUTH_BIOMETRIC_STRONG;
924         private boolean mUserPresenceRequired = false;
925         private byte[] mAttestationChallenge = null;
926         private boolean mDevicePropertiesAttestationIncluded = false;
927         private int[] mAttestationIds = new int[0];
928         private boolean mUniqueIdIncluded = false;
929         private boolean mUserAuthenticationValidWhileOnBody;
930         private boolean mInvalidatedByBiometricEnrollment = true;
931         private boolean mIsStrongBoxBacked = false;
932         private boolean mUserConfirmationRequired;
933         private boolean mUnlockedDeviceRequired = false;
934         private boolean mCriticalToDeviceEncryption = false;
935         private int mMaxUsageCount = KeyProperties.UNRESTRICTED_USAGE_COUNT;
936         private String mAttestKeyAlias = null;
937         private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID;
938 
939         /**
940          * Creates a new instance of the {@code Builder}.
941          *
942          * @param keystoreAlias alias of the entry in which the generated key will appear in
943          *        Android KeyStore. Must not be empty.
944          * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
945          *        used. Attempts to use the key for any other purpose will be rejected.
946          *
947          *        <p>If the set of purposes for which the key can be used does not contain
948          *        {@link KeyProperties#PURPOSE_SIGN}, the self-signed certificate generated by
949          *        {@link KeyPairGenerator} of {@code AndroidKeyStore} provider will contain an
950          *        invalid signature. This is OK if the certificate is only used for obtaining the
951          *        public key from Android KeyStore.
952          *
953          *        <p>See {@link KeyProperties}.{@code PURPOSE} flags.
954          */
Builder(@onNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes)955         public Builder(@NonNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes) {
956             if (keystoreAlias == null) {
957                 throw new NullPointerException("keystoreAlias == null");
958             } else if (keystoreAlias.isEmpty()) {
959                 throw new IllegalArgumentException("keystoreAlias must not be empty");
960             }
961             mKeystoreAlias = keystoreAlias;
962             mPurposes = purposes;
963         }
964 
965         /**
966          * A Builder constructor taking in an already-built KeyGenParameterSpec, useful for
967          * changing values of the KeyGenParameterSpec quickly.
968          * @hide Should be used internally only.
969          */
Builder(@onNull KeyGenParameterSpec sourceSpec)970         public Builder(@NonNull KeyGenParameterSpec sourceSpec) {
971             this(sourceSpec.getKeystoreAlias(), sourceSpec.getPurposes());
972             mNamespace = sourceSpec.getNamespace();
973             mKeySize = sourceSpec.getKeySize();
974             mSpec = sourceSpec.getAlgorithmParameterSpec();
975             mCertificateSubject = sourceSpec.getCertificateSubject();
976             mCertificateSerialNumber = sourceSpec.getCertificateSerialNumber();
977             mCertificateNotBefore = sourceSpec.getCertificateNotBefore();
978             mCertificateNotAfter = sourceSpec.getCertificateNotAfter();
979             mKeyValidityStart = sourceSpec.getKeyValidityStart();
980             mKeyValidityForOriginationEnd = sourceSpec.getKeyValidityForOriginationEnd();
981             mKeyValidityForConsumptionEnd = sourceSpec.getKeyValidityForConsumptionEnd();
982             mPurposes = sourceSpec.getPurposes();
983             if (sourceSpec.isDigestsSpecified()) {
984                 mDigests = sourceSpec.getDigests();
985             }
986             mEncryptionPaddings = sourceSpec.getEncryptionPaddings();
987             mSignaturePaddings = sourceSpec.getSignaturePaddings();
988             mBlockModes = sourceSpec.getBlockModes();
989             mRandomizedEncryptionRequired = sourceSpec.isRandomizedEncryptionRequired();
990             mUserAuthenticationRequired = sourceSpec.isUserAuthenticationRequired();
991             mUserAuthenticationValidityDurationSeconds =
992                 sourceSpec.getUserAuthenticationValidityDurationSeconds();
993             mUserAuthenticationType = sourceSpec.getUserAuthenticationType();
994             mUserPresenceRequired = sourceSpec.isUserPresenceRequired();
995             mAttestationChallenge = sourceSpec.getAttestationChallenge();
996             mDevicePropertiesAttestationIncluded =
997                     sourceSpec.isDevicePropertiesAttestationIncluded();
998             mAttestationIds = sourceSpec.getAttestationIds();
999             mUniqueIdIncluded = sourceSpec.isUniqueIdIncluded();
1000             mUserAuthenticationValidWhileOnBody = sourceSpec.isUserAuthenticationValidWhileOnBody();
1001             mInvalidatedByBiometricEnrollment = sourceSpec.isInvalidatedByBiometricEnrollment();
1002             mIsStrongBoxBacked = sourceSpec.isStrongBoxBacked();
1003             mUserConfirmationRequired = sourceSpec.isUserConfirmationRequired();
1004             mUnlockedDeviceRequired = sourceSpec.isUnlockedDeviceRequired();
1005             mCriticalToDeviceEncryption = sourceSpec.isCriticalToDeviceEncryption();
1006             mMaxUsageCount = sourceSpec.getMaxUsageCount();
1007             mAttestKeyAlias = sourceSpec.getAttestKeyAlias();
1008             mBoundToSecureUserId = sourceSpec.getBoundToSpecificSecureUserId();
1009         }
1010 
1011         /**
1012          * Sets the UID which will own the key.
1013          *
1014          * Such cross-UID access is permitted to a few system UIDs and only to a few other UIDs
1015          * (e.g., Wi-Fi, VPN) all of which are system.
1016          *
1017          * @param uid UID or {@code -1} for the UID of the current process.
1018          *
1019          * @deprecated Setting the UID of the target namespace is based on a hardcoded
1020          * hack in the Keystore service. This is no longer supported with Keystore 2.0/Android S.
1021          * Instead, dedicated non UID based namespaces can be configured in SEPolicy using
1022          * the keystore2_key_contexts files. The functionality of this method will be supported
1023          * by mapping knows special UIDs, such as WIFI, to the newly configured SELinux based
1024          * namespaces. Unknown UIDs will yield {@link IllegalArgumentException}.
1025          *
1026          * @hide
1027          */
1028         @SystemApi
1029         @NonNull
1030         @Deprecated
setUid(int uid)1031         public Builder setUid(int uid) {
1032             mNamespace = KeyProperties.legacyUidToNamespace(uid);
1033             return this;
1034         }
1035 
1036         /**
1037          * Set the designated SELinux namespace that the key shall live in. The caller must
1038          * have sufficient permissions to install a key in the given namespace. Namespaces
1039          * can be created using SEPolicy. The keystore2_key_contexts files map numeric
1040          * namespaces to SELinux labels, and SEPolicy can be used to grant access to these
1041          * namespaces to the desired target context. This is the preferred way to share
1042          * keys between system and vendor components, e.g., WIFI settings and WPA supplicant.
1043          *
1044          * @param namespace Numeric SELinux namespace as configured in keystore2_key_contexts
1045          *         of Android's SEPolicy.
1046          *         See <a href="https://source.android.com/security/keystore#access-control">
1047          *             Keystore 2.0 access control</a>
1048          * @return this Builder object.
1049          *
1050          * @hide
1051          */
1052         @SystemApi
1053         @NonNull
setNamespace(@eyProperties.Namespace int namespace)1054         public Builder setNamespace(@KeyProperties.Namespace int namespace) {
1055             mNamespace = namespace;
1056             return this;
1057         }
1058 
1059         /**
1060          * Sets the size (in bits) of the key to be generated. For instance, for RSA keys this sets
1061          * the modulus size, for EC keys this selects a curve with a matching field size, and for
1062          * symmetric keys this sets the size of the bitstring which is their key material.
1063          *
1064          * <p>The default key size is specific to each key algorithm. If key size is not set
1065          * via this method, it should be looked up from the algorithm-specific parameters (if any)
1066          * provided via
1067          * {@link #setAlgorithmParameterSpec(AlgorithmParameterSpec) setAlgorithmParameterSpec}.
1068          */
1069         @NonNull
setKeySize(int keySize)1070         public Builder setKeySize(int keySize) {
1071             if (keySize < 0) {
1072                 throw new IllegalArgumentException("keySize < 0");
1073             }
1074             mKeySize = keySize;
1075             return this;
1076         }
1077 
1078         /**
1079          * Sets the algorithm-specific key generation parameters. For example, for RSA keys this may
1080          * be an instance of {@link java.security.spec.RSAKeyGenParameterSpec} whereas for EC keys
1081          * this may be an instance of {@link java.security.spec.ECGenParameterSpec}.
1082          *
1083          * <p>These key generation parameters must match other explicitly set parameters (if any),
1084          * such as key size.
1085          */
setAlgorithmParameterSpec(@onNull AlgorithmParameterSpec spec)1086         public Builder setAlgorithmParameterSpec(@NonNull AlgorithmParameterSpec spec) {
1087             if (spec == null) {
1088                 throw new NullPointerException("spec == null");
1089             }
1090             mSpec = spec;
1091             return this;
1092         }
1093 
1094         /**
1095          * Sets the subject used for the self-signed certificate of the generated key pair.
1096          *
1097          * <p>By default, the subject is {@code CN=fake}.
1098          */
1099         @NonNull
setCertificateSubject(@onNull X500Principal subject)1100         public Builder setCertificateSubject(@NonNull X500Principal subject) {
1101             if (subject == null) {
1102                 throw new NullPointerException("subject == null");
1103             }
1104             mCertificateSubject = subject;
1105             return this;
1106         }
1107 
1108         /**
1109          * Sets the serial number used for the self-signed certificate of the generated key pair.
1110          *
1111          * <p>By default, the serial number is {@code 1}.
1112          */
1113         @NonNull
setCertificateSerialNumber(@onNull BigInteger serialNumber)1114         public Builder setCertificateSerialNumber(@NonNull BigInteger serialNumber) {
1115             if (serialNumber == null) {
1116                 throw new NullPointerException("serialNumber == null");
1117             }
1118             mCertificateSerialNumber = serialNumber;
1119             return this;
1120         }
1121 
1122         /**
1123          * Sets the start of the validity period for the self-signed certificate of the generated
1124          * key pair.
1125          *
1126          * <p>By default, this date is {@code Jan 1 1970}.
1127          */
1128         @NonNull
setCertificateNotBefore(@onNull Date date)1129         public Builder setCertificateNotBefore(@NonNull Date date) {
1130             if (date == null) {
1131                 throw new NullPointerException("date == null");
1132             }
1133             mCertificateNotBefore = Utils.cloneIfNotNull(date);
1134             return this;
1135         }
1136 
1137         /**
1138          * Sets the end of the validity period for the self-signed certificate of the generated key
1139          * pair.
1140          *
1141          * <p>By default, this date is {@code Jan 1 2048}.
1142          */
1143         @NonNull
setCertificateNotAfter(@onNull Date date)1144         public Builder setCertificateNotAfter(@NonNull Date date) {
1145             if (date == null) {
1146                 throw new NullPointerException("date == null");
1147             }
1148             mCertificateNotAfter = Utils.cloneIfNotNull(date);
1149             return this;
1150         }
1151 
1152         /**
1153          * Sets the time instant before which the key is not yet valid.
1154          *
1155          * <p>By default, the key is valid at any instant.
1156          *
1157          * @see #setKeyValidityEnd(Date)
1158          */
1159         @NonNull
setKeyValidityStart(Date startDate)1160         public Builder setKeyValidityStart(Date startDate) {
1161             mKeyValidityStart = Utils.cloneIfNotNull(startDate);
1162             return this;
1163         }
1164 
1165         /**
1166          * Sets the time instant after which the key is no longer valid.
1167          *
1168          * <p>By default, the key is valid at any instant.
1169          *
1170          * @see #setKeyValidityStart(Date)
1171          * @see #setKeyValidityForConsumptionEnd(Date)
1172          * @see #setKeyValidityForOriginationEnd(Date)
1173          */
1174         @NonNull
setKeyValidityEnd(Date endDate)1175         public Builder setKeyValidityEnd(Date endDate) {
1176             setKeyValidityForOriginationEnd(endDate);
1177             setKeyValidityForConsumptionEnd(endDate);
1178             return this;
1179         }
1180 
1181         /**
1182          * Sets the time instant after which the key is no longer valid for encryption and signing.
1183          *
1184          * <p>By default, the key is valid at any instant.
1185          *
1186          * @see #setKeyValidityForConsumptionEnd(Date)
1187          */
1188         @NonNull
setKeyValidityForOriginationEnd(Date endDate)1189         public Builder setKeyValidityForOriginationEnd(Date endDate) {
1190             mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
1191             return this;
1192         }
1193 
1194         /**
1195          * Sets the time instant after which the key is no longer valid for decryption and
1196          * verification.
1197          *
1198          * <p>By default, the key is valid at any instant.
1199          *
1200          * @see #setKeyValidityForOriginationEnd(Date)
1201          */
1202         @NonNull
setKeyValidityForConsumptionEnd(Date endDate)1203         public Builder setKeyValidityForConsumptionEnd(Date endDate) {
1204             mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
1205             return this;
1206         }
1207 
1208         /**
1209          * Sets the set of digests algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which
1210          * the key can be used. Attempts to use the key with any other digest algorithm will be
1211          * rejected.
1212          *
1213          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
1214          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
1215          * HMAC keys, the default is the digest associated with the key algorithm (e.g.,
1216          * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
1217          * for more than one digest.
1218          *
1219          * <p>For private keys used for TLS/SSL client or server authentication it is usually
1220          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
1221          * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
1222          * a private key to sign it.
1223          *
1224          * <p>See {@link KeyProperties}.{@code DIGEST} constants.
1225          */
1226         @NonNull
setDigests(@eyProperties.DigestEnum String... digests)1227         public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
1228             mDigests = ArrayUtils.cloneIfNotEmpty(digests);
1229             return this;
1230         }
1231 
1232         /**
1233          * Sets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OAEPPadding},
1234          * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
1235          * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
1236          * rejected.
1237          *
1238          * <p>This must be specified for keys which are used for encryption/decryption.
1239          *
1240          * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
1241          * is usually necessary to authorize the use of no/any padding
1242          * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
1243          * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
1244          * required by some cipher suites, and some stacks request decryption using no padding
1245          * whereas others request PKCS#1 padding.
1246          *
1247          * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
1248          */
1249         @NonNull
setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)1250         public Builder setEncryptionPaddings(
1251                 @KeyProperties.EncryptionPaddingEnum String... paddings) {
1252             mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
1253             return this;
1254         }
1255 
1256         /**
1257          * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
1258          * can be used when signing/verifying. Attempts to use the key with any other padding scheme
1259          * will be rejected.
1260          *
1261          * <p>This must be specified for RSA keys which are used for signing/verification.
1262          *
1263          * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
1264          */
1265         @NonNull
setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)1266         public Builder setSignaturePaddings(
1267                 @KeyProperties.SignaturePaddingEnum String... paddings) {
1268             mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
1269             return this;
1270         }
1271 
1272         /**
1273          * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
1274          * used when encrypting/decrypting. Attempts to use the key with any other block modes will
1275          * be rejected.
1276          *
1277          * <p>This must be specified for symmetric encryption/decryption keys.
1278          *
1279          * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
1280          */
1281         @NonNull
setBlockModes(@eyProperties.BlockModeEnum String... blockModes)1282         public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
1283             mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
1284             return this;
1285         }
1286 
1287         /**
1288          * Sets whether encryption using this key must be sufficiently randomized to produce
1289          * different ciphertexts for the same plaintext every time. The formal cryptographic
1290          * property being required is <em>indistinguishability under chosen-plaintext attack
1291          * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
1292          * of weaknesses due to which ciphertext may leak information about plaintext. For example,
1293          * if a given plaintext always produces the same ciphertext, an attacker may see the
1294          * repeated ciphertexts and be able to deduce something about the plaintext.
1295          *
1296          * <p>By default, {@code IND-CPA} is required.
1297          *
1298          * <p>When {@code IND-CPA} is required:
1299          * <ul>
1300          * <li>encryption/decryption transformation which do not offer {@code IND-CPA}, such as
1301          * {@code ECB} with a symmetric encryption algorithm, or RSA encryption/decryption without
1302          * padding, are prohibited;</li>
1303          * <li>in block modes which use an IV, such as {@code GCM}, {@code CBC}, and {@code CTR},
1304          * caller-provided IVs are rejected when encrypting, to ensure that only random IVs are
1305          * used.</li>
1306          * </ul>
1307          *
1308          * <p>Before disabling this requirement, consider the following approaches instead:
1309          * <ul>
1310          * <li>If you are generating a random IV for encryption and then initializing a {@code}
1311          * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
1312          * instead. This will occur if the {@code Cipher} is initialized for encryption without an
1313          * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
1314          * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
1315          * random, such as the name of the file being encrypted, or transaction ID, or password,
1316          * or a device identifier), consider changing your design to use a random IV which will then
1317          * be provided in addition to the ciphertext to the entities which need to decrypt the
1318          * ciphertext.</li>
1319          * <li>If you are using RSA encryption without padding, consider switching to encryption
1320          * padding schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
1321          * </ul>
1322          */
1323         @NonNull
setRandomizedEncryptionRequired(boolean required)1324         public Builder setRandomizedEncryptionRequired(boolean required) {
1325             mRandomizedEncryptionRequired = required;
1326             return this;
1327         }
1328 
1329         /**
1330          * Sets whether this key is authorized to be used only if the user has been authenticated.
1331          *
1332          * <p>By default, the key is authorized to be used regardless of whether the user has been
1333          * authenticated.
1334          *
1335          * <p>When user authentication is required:
1336          * <ul>
1337          * <li>The key can only be generated if secure lock screen is set up (see
1338          * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
1339          * authentication takes place for every use of the key (see
1340          * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
1341          * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
1342          * <li>The use of the key must be authorized by the user by authenticating to this Android
1343          * device using a subset of their secure lock screen credentials such as
1344          * password/PIN/pattern or biometric.
1345          * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
1346          * information</a>.
1347          * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
1348          * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
1349          * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
1350          * Additionally, if the key requires that user authentication takes place for every use of
1351          * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
1352          * no more biometrics are enrolled, unless {@link
1353          * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
1354          * enrollment. Attempts to initialize cryptographic operations using such keys will throw
1355          * {@link KeyPermanentlyInvalidatedException}.</li>
1356          * </ul>
1357          *
1358          * <p>This authorization applies only to secret key and private key operations. Public key
1359          * operations are not restricted.
1360          *
1361          * @see #setUserAuthenticationValidityDurationSeconds(int)
1362          * @see KeyguardManager#isDeviceSecure()
1363          * @see BiometricManager#canAuthenticate()
1364          */
1365         @NonNull
setUserAuthenticationRequired(boolean required)1366         public Builder setUserAuthenticationRequired(boolean required) {
1367             mUserAuthenticationRequired = required;
1368             return this;
1369         }
1370 
1371         /**
1372          * Sets whether this key is authorized to be used only for messages confirmed by the
1373          * user.
1374          *
1375          * Confirmation is separate from user authentication (see
1376          * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require
1377          * confirmation but not user authentication, or user authentication but not confirmation,
1378          * or both. Confirmation verifies that some user with physical possession of the device has
1379          * approved a displayed message. User authentication verifies that the correct user is
1380          * present and has authenticated.
1381          *
1382          * <p>This authorization applies only to secret key and private key operations. Public key
1383          * operations are not restricted.
1384          *
1385          * See {@link android.security.ConfirmationPrompt} class for
1386          * more details about user confirmations.
1387          */
1388         @NonNull
setUserConfirmationRequired(boolean required)1389         public Builder setUserConfirmationRequired(boolean required) {
1390             mUserConfirmationRequired = required;
1391             return this;
1392         }
1393 
1394         /**
1395          * Sets the duration of time (seconds) for which this key is authorized to be used after the
1396          * user is successfully authenticated. This has effect if the key requires user
1397          * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
1398          *
1399          * <p>By default, if user authentication is required, it must take place for every use of
1400          * the key.
1401          *
1402          * <p>Cryptographic operations involving keys which require user authentication to take
1403          * place for every operation can only use biometric authentication. This is achieved by
1404          * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
1405          * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
1406          * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
1407          * the cryptographic operation only if the authentication flow succeeds.
1408          *
1409          * <p>Cryptographic operations involving keys which are authorized to be used for a duration
1410          * of time after a successful user authentication event can only use secure lock screen
1411          * authentication. These cryptographic operations will throw
1412          * {@link UserNotAuthenticatedException} during initialization if the user needs to be
1413          * authenticated to proceed. This situation can be resolved by the user unlocking the secure
1414          * lock screen of the Android or by going through the confirm credential flow initiated by
1415          * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
1416          * Once resolved, initializing a new cryptographic operation using this key (or any other
1417          * key which is authorized to be used for a fixed duration of time after user
1418          * authentication) should succeed provided the user authentication flow completed
1419          * successfully.
1420          *
1421          * @param seconds duration in seconds or {@code -1} if user authentication must take place
1422          *        for every use of the key.
1423          *
1424          * @see #setUserAuthenticationRequired(boolean)
1425          * @see BiometricPrompt
1426          * @see BiometricPrompt.CryptoObject
1427          * @see KeyguardManager
1428          * @deprecated See {@link #setUserAuthenticationParameters(int, int)}
1429          */
1430         @Deprecated
1431         @NonNull
setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)1432         public Builder setUserAuthenticationValidityDurationSeconds(
1433                 @IntRange(from = -1) int seconds) {
1434             if (seconds < -1) {
1435                 throw new IllegalArgumentException("seconds must be -1 or larger");
1436             }
1437             if (seconds == -1) {
1438                 return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
1439             }
1440             return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL
1441                                                             | KeyProperties.AUTH_BIOMETRIC_STRONG);
1442         }
1443 
1444         /**
1445          * Sets the duration of time (seconds) and authorization type for which this key is
1446          * authorized to be used after the user is successfully authenticated. This has effect if
1447          * the key requires user authentication for its use (see
1448          * {@link #setUserAuthenticationRequired(boolean)}).
1449          *
1450          * <p>By default, if user authentication is required, it must take place for every use of
1451          * the key.
1452          *
1453          * <p>These cryptographic operations will throw {@link UserNotAuthenticatedException} during
1454          * initialization if the user needs to be authenticated to proceed. This situation can be
1455          * resolved by the user authenticating with the appropriate biometric or credential as
1456          * required by the key. See {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)}
1457          * and {@link BiometricManager.Authenticators}.
1458          *
1459          * <p>Once resolved, initializing a new cryptographic operation using this key (or any other
1460          * key which is authorized to be used for a fixed duration of time after user
1461          * authentication) should succeed provided the user authentication flow completed
1462          * successfully.
1463          *
1464          * @param timeout duration in seconds or {@code 0} if user authentication must take place
1465          *        for every use of the key.
1466          * @param type set of authentication types which can authorize use of the key. See
1467          *        {@link KeyProperties}.{@code AUTH} flags.
1468          *
1469          * @see #setUserAuthenticationRequired(boolean)
1470          * @see BiometricPrompt
1471          * @see BiometricPrompt.CryptoObject
1472          * @see KeyguardManager
1473          */
1474         @NonNull
setUserAuthenticationParameters(@ntRangefrom = 0) int timeout, @KeyProperties.AuthEnum int type)1475         public Builder setUserAuthenticationParameters(@IntRange(from = 0) int timeout,
1476                                                        @KeyProperties.AuthEnum int type) {
1477             if (timeout < 0) {
1478                 throw new IllegalArgumentException("timeout must be 0 or larger");
1479             }
1480             mUserAuthenticationValidityDurationSeconds = timeout;
1481             mUserAuthenticationType = type;
1482             return this;
1483         }
1484 
1485         /**
1486          * Sets whether a test of user presence is required to be performed between the
1487          * {@code Signature.initSign()} and {@code Signature.sign()} method calls.
1488          * It requires that the KeyStore implementation have a direct way to validate the user
1489          * presence for example a KeyStore hardware backed strongbox can use a button press that
1490          * is observable in hardware. A test for user presence is tangential to authentication. The
1491          * test can be part of an authentication step as long as this step can be validated by the
1492          * hardware protecting the key and cannot be spoofed. For example, a physical button press
1493          * can be used as a test of user presence if the other pins connected to the button are not
1494          * able to simulate a button press.There must be no way for the primary processor to fake a
1495          * button press, or that button must not be used as a test of user presence.
1496          */
1497         @NonNull
setUserPresenceRequired(boolean required)1498         public Builder setUserPresenceRequired(boolean required) {
1499             mUserPresenceRequired = required;
1500             return this;
1501         }
1502 
1503         /**
1504          * Sets whether an attestation certificate will be generated for this key pair, and what
1505          * challenge value will be placed in the certificate.  The attestation certificate chain
1506          * can be retrieved with with {@link java.security.KeyStore#getCertificateChain(String)}.
1507          *
1508          * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for
1509          * this key pair will contain an extension that describes the details of the key's
1510          * configuration and authorizations, including the {@code attestationChallenge} value. If
1511          * the key is in secure hardware, and if the secure hardware supports attestation, the
1512          * certificate will be signed by a chain of certificates rooted at a trustworthy CA key.
1513          * Otherwise the chain will be rooted at an untrusted certificate.
1514          *
1515          * <p>The purpose of the challenge value is to enable relying parties to verify that the key
1516          * was created in response to a specific request. If attestation is desired but no
1517          * challenged is needed, any non-{@code null} value may be used, including an empty byte
1518          * array.
1519          *
1520          * <p>If {@code attestationChallenge} is {@code null}, and this spec is used to generate an
1521          * asymmetric (RSA or EC) key pair, the public key certificate will be self-signed if the
1522          * key has purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}. If the key
1523          * does not have purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}, it is
1524          * not possible to use the key to sign a certificate, so the public key certificate will
1525          * contain a dummy signature.
1526          *
1527          * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
1528          * {@link #getAttestationChallenge()} returns non-null and the spec is used to generate a
1529          * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
1530          * {@link java.security.InvalidAlgorithmParameterException}.
1531          */
1532         @NonNull
setAttestationChallenge(byte[] attestationChallenge)1533         public Builder setAttestationChallenge(byte[] attestationChallenge) {
1534             mAttestationChallenge = attestationChallenge;
1535             return this;
1536         }
1537 
1538         /**
1539          * Sets whether to include the base device properties in the attestation certificate.
1540          *
1541          * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for
1542          * this key pair will contain an extension that describes the details of the key's
1543          * configuration and authorizations, including the device properties values (brand, device,
1544          * manufacturer, model, product). These should be the same as in ({@link Build#BRAND},
1545          * {@link Build#DEVICE}, {@link Build#MANUFACTURER}, {@link Build#MODEL},
1546          * {@link Build#PRODUCT}). The attestation certificate chain can
1547          * be retrieved with {@link java.security.KeyStore#getCertificateChain(String)}.
1548          *
1549          * <p> If {@code attestationChallenge} is {@code null}, the public key certificate for
1550          * this key pair will not contain the extension with the requested attested values.
1551          *
1552          * <p> {@link javax.crypto.KeyGenerator#generateKey()} will throw
1553          * {@link java.security.ProviderException} if device properties attestation fails or is not
1554          * supported.
1555          */
1556         @NonNull
setDevicePropertiesAttestationIncluded( boolean devicePropertiesAttestationIncluded)1557         public Builder setDevicePropertiesAttestationIncluded(
1558                 boolean devicePropertiesAttestationIncluded) {
1559             mDevicePropertiesAttestationIncluded = devicePropertiesAttestationIncluded;
1560             return this;
1561         }
1562 
1563         /**
1564          * @hide
1565          * Sets which IDs to attest in the attestation certificate for the key. The acceptable
1566          * values in this integer array are the enums specified in
1567          * {@link android.security.keystore.AttestationUtils}
1568          *
1569          * @param attestationIds the array of ID types to attest to in the certificate.
1570          *
1571          * @see android.security.keystore.AttestationUtils#ID_TYPE_SERIAL
1572          * @see android.security.keystore.AttestationUtils#ID_TYPE_IMEI
1573          * @see android.security.keystore.AttestationUtils#ID_TYPE_MEID
1574          * @see android.security.keystore.AttestationUtils#USE_INDIVIDUAL_ATTESTATION
1575          */
1576         @SystemApi
1577         @NonNull
setAttestationIds(@onNull int[] attestationIds)1578         public Builder setAttestationIds(@NonNull int[] attestationIds) {
1579             mAttestationIds = attestationIds;
1580             return this;
1581         }
1582 
1583         /**
1584          * @hide Only system apps can use this method.
1585          *
1586          * Sets whether to include a temporary unique ID field in the attestation certificate.
1587          */
1588         @UnsupportedAppUsage
1589         @TestApi
1590         @NonNull
setUniqueIdIncluded(boolean uniqueIdIncluded)1591         public Builder setUniqueIdIncluded(boolean uniqueIdIncluded) {
1592             mUniqueIdIncluded = uniqueIdIncluded;
1593             return this;
1594         }
1595 
1596         /**
1597          * Sets whether the key will remain authorized only until the device is removed from the
1598          * user's body up to the limit of the authentication validity period (see
1599          * {@link #setUserAuthenticationValidityDurationSeconds} and
1600          * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
1601          * user's body, the key will be considered unauthorized and the user will need to
1602          * re-authenticate to use it. For keys without an authentication validity period this
1603          * parameter has no effect.
1604          *
1605          * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
1606          * effect; the device will always be considered to be "on-body" and the key will therefore
1607          * remain authorized until the validity period ends.
1608          *
1609          * @param remainsValid if {@code true}, and if the device supports on-body detection, key
1610          * will be invalidated when the device is removed from the user's body or when the
1611          * authentication validity expires, whichever occurs first.
1612          */
1613         @NonNull
setUserAuthenticationValidWhileOnBody(boolean remainsValid)1614         public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
1615             mUserAuthenticationValidWhileOnBody = remainsValid;
1616             return this;
1617         }
1618 
1619         /**
1620          * Sets whether this key should be invalidated on biometric enrollment.  This
1621          * applies only to keys which require user authentication (see {@link
1622          * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
1623          * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
1624          * valid for biometric authentication only.
1625          *
1626          * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
1627          * biometric authentication only are <em>irreversibly invalidated</em> when a new
1628          * biometric is enrolled, or when all existing biometrics are deleted.  That may be
1629          * changed by calling this method with {@code invalidateKey} set to {@code false}.
1630          *
1631          * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
1632          * improves security by ensuring that an unauthorized person who obtains the password can't
1633          * gain the use of biometric-authenticated keys by enrolling their own biometric.  However,
1634          * invalidating keys makes key-dependent operations impossible, requiring some fallback
1635          * procedure to authenticate the user and set up a new key.
1636          */
1637         @NonNull
setInvalidatedByBiometricEnrollment(boolean invalidateKey)1638         public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
1639             mInvalidatedByBiometricEnrollment = invalidateKey;
1640             return this;
1641         }
1642 
1643         /**
1644          * Sets whether this key should be protected by a StrongBox security chip.
1645          */
1646         @NonNull
setIsStrongBoxBacked(boolean isStrongBoxBacked)1647         public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
1648             mIsStrongBoxBacked = isStrongBoxBacked;
1649             return this;
1650         }
1651 
1652         /**
1653          * Sets whether the keystore requires the screen to be unlocked before allowing decryption
1654          * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
1655          * key while the screen is locked will fail. A locked device requires a PIN, password,
1656          * biometric, or other trusted factor to access. While the screen is locked, any associated
1657          * public key can still be used (e.g for signature verification).
1658          */
1659         @NonNull
setUnlockedDeviceRequired(boolean unlockedDeviceRequired)1660         public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
1661             mUnlockedDeviceRequired = unlockedDeviceRequired;
1662             return this;
1663         }
1664 
1665         /**
1666          * Set whether this key is critical to the device encryption flow
1667          *
1668          * This is a special flag only available to system servers to indicate the current key
1669          * is part of the device encryption flow. Setting this flag causes the key to not
1670          * be cryptographically bound to the LSKF even if the key is otherwise authentication
1671          * bound.
1672          *
1673          * @hide
1674          */
setCriticalToDeviceEncryption(boolean critical)1675         public Builder setCriticalToDeviceEncryption(boolean critical) {
1676             mCriticalToDeviceEncryption = critical;
1677             return this;
1678         }
1679 
1680         /**
1681          * Sets the maximum number of times the key is allowed to be used. After every use of the
1682          * key, the use counter will decrease. This authorization applies only to secret key and
1683          * private key operations. Public key operations are not restricted. For example, after
1684          * successfully encrypting and decrypting data using methods such as
1685          * {@link Cipher#doFinal()}, the use counter of the secret key will decrease. After
1686          * successfully signing data using methods such as {@link Signature#sign()}, the use
1687          * counter of the private key will decrease.
1688          *
1689          * When the use counter is depleted, the key will be marked for deletion by Android
1690          * Keystore and any subsequent attempt to use the key will throw
1691          * {@link KeyPermanentlyInvalidatedException}. There is no key to be loaded from the
1692          * Android Keystore once the exhausted key is permanently deleted, as if the key never
1693          * existed before.
1694          *
1695          * <p>By default, there is no restriction on the usage of key.
1696          *
1697          * <p>Some secure hardware may not support this feature at all, in which case it will
1698          * be enforced in software, some secure hardware may support it but only with
1699          * maxUsageCount = 1, and some secure hardware may support it with larger value
1700          * of maxUsageCount.
1701          *
1702          * <p>The PackageManger feature flags:
1703          * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_SINGLE_USE_KEY} and
1704          * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_LIMITED_USE_KEY} can be used
1705          * to check whether the secure hardware cannot enforce this feature, can only enforce it
1706          * with maxUsageCount = 1, or can enforce it with larger value of maxUsageCount.
1707          *
1708          * @param maxUsageCount maximum number of times the key is allowed to be used or
1709          *        {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there is no restriction on the
1710          *        usage.
1711          */
1712         @NonNull
setMaxUsageCount(int maxUsageCount)1713         public Builder setMaxUsageCount(int maxUsageCount) {
1714             if (maxUsageCount == KeyProperties.UNRESTRICTED_USAGE_COUNT || maxUsageCount > 0) {
1715                 mMaxUsageCount = maxUsageCount;
1716                 return this;
1717             }
1718             throw new IllegalArgumentException("maxUsageCount is not valid");
1719         }
1720 
1721         /**
1722          * Sets the alias of the attestation key that will be used to sign the attestation
1723          * certificate for the generated key pair, if an attestation challenge is set with {@link
1724          * #setAttestationChallenge}.  If an attestKeyAlias is set but no challenge, {@link
1725          * java.security.KeyPairGenerator#initialize} will throw {@link
1726          * java.security.InvalidAlgorithmParameterException}.
1727          *
1728          * <p>If the attestKeyAlias is set to null (the default), Android Keystore will select an
1729          * appropriate system-provided attestation signing key.  If not null, the alias must
1730          * reference an Android Keystore Key that was created with {@link
1731          * android.security.keystore.KeyProperties#PURPOSE_ATTEST_KEY}, or key generation will throw
1732          * {@link java.security.InvalidAlgorithmParameterException}.
1733          *
1734          * @param attestKeyAlias the alias of the attestation key to be used to sign the
1735          *        attestation certificate.
1736          */
1737         @NonNull
setAttestKeyAlias(@ullable String attestKeyAlias)1738         public Builder setAttestKeyAlias(@Nullable String attestKeyAlias) {
1739             mAttestKeyAlias = attestKeyAlias;
1740             return this;
1741         }
1742 
1743         /**
1744          * Set the secure user id that this key should be bound to.
1745          *
1746          * Normally an authentication-bound key is tied to the secure user id of the current user
1747          * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the
1748          * authenticator id of the current biometric set for keys requiring explicit biometric
1749          * authorization). If this parameter is set (this method returning non-zero value), the key
1750          * should be tied to the specified secure user id, overriding the logic above.
1751          *
1752          * This is only applicable when {@link #setUserAuthenticationRequired} is set to
1753          * {@code true}
1754          *
1755          * @see KeyGenParameterSpec#getBoundToSpecificSecureUserId()
1756          * @hide
1757          */
1758         @NonNull
setBoundToSpecificSecureUserId(long secureUserId)1759         public Builder setBoundToSpecificSecureUserId(long secureUserId) {
1760             mBoundToSecureUserId = secureUserId;
1761             return this;
1762         }
1763 
1764         /**
1765          * Builds an instance of {@code KeyGenParameterSpec}.
1766          */
1767         @NonNull
build()1768         public KeyGenParameterSpec build() {
1769             return new KeyGenParameterSpec(
1770                     mKeystoreAlias,
1771                     mNamespace,
1772                     mKeySize,
1773                     mSpec,
1774                     mCertificateSubject,
1775                     mCertificateSerialNumber,
1776                     mCertificateNotBefore,
1777                     mCertificateNotAfter,
1778                     mKeyValidityStart,
1779                     mKeyValidityForOriginationEnd,
1780                     mKeyValidityForConsumptionEnd,
1781                     mPurposes,
1782                     mDigests,
1783                     mEncryptionPaddings,
1784                     mSignaturePaddings,
1785                     mBlockModes,
1786                     mRandomizedEncryptionRequired,
1787                     mUserAuthenticationRequired,
1788                     mUserAuthenticationValidityDurationSeconds,
1789                     mUserAuthenticationType,
1790                     mUserPresenceRequired,
1791                     mAttestationChallenge,
1792                     mDevicePropertiesAttestationIncluded,
1793                     mAttestationIds,
1794                     mUniqueIdIncluded,
1795                     mUserAuthenticationValidWhileOnBody,
1796                     mInvalidatedByBiometricEnrollment,
1797                     mIsStrongBoxBacked,
1798                     mUserConfirmationRequired,
1799                     mUnlockedDeviceRequired,
1800                     mCriticalToDeviceEncryption,
1801                     mMaxUsageCount,
1802                     mAttestKeyAlias,
1803                     mBoundToSecureUserId);
1804         }
1805     }
1806 }
1807