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