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