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