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