blob: e3f43efff72b08ab112a2cb682f937bca60ece88 [file] [log] [blame]
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001/*
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
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070019import android.annotation.IntRange;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
Shawn Willden13e230f2018-04-10 17:21:39 -060022import android.annotation.TestApi;
Mathew Inwoode420f8b2018-08-16 18:40:47 +010023import android.annotation.UnsupportedAppUsage;
Alex Klyubin83cc7a32015-06-16 10:44:11 -070024import android.app.KeyguardManager;
Kevin Chyn9374c9f2019-04-04 17:46:18 -070025import android.hardware.biometrics.BiometricManager;
26import android.hardware.biometrics.BiometricPrompt;
Brian Young5437b812018-02-23 18:04:20 +000027import android.security.GateKeeper;
Alex Klyubin3876b1b2015-09-09 14:55:03 -070028import android.security.KeyStore;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070029import android.text.TextUtils;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070030
31import java.math.BigInteger;
32import java.security.KeyPairGenerator;
Alex Klyubin83cc7a32015-06-16 10:44:11 -070033import java.security.Signature;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070034import java.security.cert.Certificate;
35import java.security.spec.AlgorithmParameterSpec;
36import java.util.Date;
37
38import javax.crypto.Cipher;
39import javax.crypto.KeyGenerator;
Alex Klyubin83cc7a32015-06-16 10:44:11 -070040import javax.crypto.Mac;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070041import javax.security.auth.x500.X500Principal;
42
43/**
44 * {@link AlgorithmParameterSpec} for initializing a {@link KeyPairGenerator} or a
45 * {@link KeyGenerator} of the <a href="{@docRoot}training/articles/keystore.html">Android Keystore
Alex Klyubin72245d72015-08-11 06:41:13 -070046 * system</a>. The spec determines authorized uses of the key, such as whether user authentication
47 * is required for using the key, what operations are authorized (e.g., signing, but not
Trevor Johns682c24e2016-04-12 10:13:47 -070048 * decryption), with what parameters (e.g., only with a particular padding scheme or digest), and
49 * the key's validity start and end dates. Key use authorizations expressed in the spec apply
50 * only to secret keys and private keys -- public keys can be used for any supported operations.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070051 *
52 * <p>To generate an asymmetric key pair or a symmetric key, create an instance of this class using
53 * the {@link Builder}, initialize a {@code KeyPairGenerator} or a {@code KeyGenerator} of the
54 * desired key type (e.g., {@code EC} or {@code AES} -- see
55 * {@link KeyProperties}.{@code KEY_ALGORITHM} constants) from the {@code AndroidKeyStore} provider
Alex Klyubin72245d72015-08-11 06:41:13 -070056 * with the {@code KeyGenParameterSpec} instance, and then generate a key or key pair using
57 * {@link KeyGenerator#generateKey()} or {@link KeyPairGenerator#generateKeyPair()}.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070058 *
59 * <p>The generated key pair or key will be returned by the generator and also stored in the Android
Alex Klyubin72245d72015-08-11 06:41:13 -070060 * Keystore under the alias specified in this spec. To obtain the secret or private key from the
61 * Android Keystore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)}
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070062 * or {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
Alex Klyubin72245d72015-08-11 06:41:13 -070063 * To obtain the public key from the Android Keystore use
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070064 * {@link java.security.KeyStore#getCertificate(String)} and then
65 * {@link Certificate#getPublicKey()}.
66 *
Alex Klyubin72245d72015-08-11 06:41:13 -070067 * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
68 * Keystore, generated private keys implement {@link java.security.interfaces.ECKey} or
69 * {@link java.security.interfaces.RSAKey} interfaces whereas public keys implement
70 * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
71 * interfaces.
72 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070073 * <p>For asymmetric key pairs, a self-signed X.509 certificate will be also generated and stored in
Alex Klyubin72245d72015-08-11 06:41:13 -070074 * the Android Keystore. This is because the {@link java.security.KeyStore} abstraction does not
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070075 * support storing key pairs without a certificate. The subject, serial number, and validity dates
76 * of the certificate can be customized in this spec. The self-signed certificate may be replaced at
77 * a later time by a certificate signed by a Certificate Authority (CA).
78 *
Alex Klyubinacb7efd2015-06-12 13:31:50 -070079 * <p>NOTE: If a private key is not authorized to sign the self-signed certificate, then the
80 * certificate will be created with an invalid signature which will not verify. Such a certificate
Alex Klyubine4928a22015-07-21 13:38:48 -070081 * is still useful because it provides access to the public key. To generate a valid signature for
82 * the certificate the key needs to be authorized for all of the following:
Alex Klyubin83cc7a32015-06-16 10:44:11 -070083 * <ul>
84 * <li>{@link KeyProperties#PURPOSE_SIGN},</li>
85 * <li>operation without requiring the user to be authenticated (see
86 * {@link Builder#setUserAuthenticationRequired(boolean)}),</li>
Alex Klyubin856aebe2015-06-23 10:54:44 -070087 * <li>signing/origination at this moment in time (see {@link Builder#setKeyValidityStart(Date)}
88 * and {@link Builder#setKeyValidityForOriginationEnd(Date)}),</li>
Alex Klyubine4928a22015-07-21 13:38:48 -070089 * <li>suitable digest,</li>
90 * <li>(RSA keys only) padding scheme {@link KeyProperties#SIGNATURE_PADDING_RSA_PKCS1}.</li>
Alex Klyubin83cc7a32015-06-16 10:44:11 -070091 * </ul>
Alex Klyubinacb7efd2015-06-12 13:31:50 -070092 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070093 * <p>NOTE: The key material of the generated symmetric and private keys is not accessible. The key
94 * material of the public keys is accessible.
95 *
Alex Klyubin1b937ee2015-06-16 09:51:20 -070096 * <p>Instances of this class are immutable.
97 *
Trevor Johns682c24e2016-04-12 10:13:47 -070098 * <p><h3>Known issues</h3>
99 * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be
100 * enforced even for public keys. To work around this issue extract the public key material to use
101 * outside of Android Keystore. For example:
102 * <pre> {@code
103 * PublicKey unrestrictedPublicKey =
104 * KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
105 * new X509EncodedKeySpec(publicKey.getEncoded()));
106 * }</pre>
107 *
Alex Klyubin72245d72015-08-11 06:41:13 -0700108 * <p><h3>Example: NIST P-256 EC key pair for signing/verification using ECDSA</h3>
109 * This example illustrates how to generate a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair
110 * in the Android KeyStore system under alias {@code key1} where the private key is authorized to be
111 * used only for signing using SHA-256, SHA-384, or SHA-512 digest and only if the user has been
Trevor Johns682c24e2016-04-12 10:13:47 -0700112 * authenticated within the last five minutes. The use of the public key is unrestricted (See Known
113 * Issues).
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700114 * <pre> {@code
115 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
Alex Klyubin72245d72015-08-11 06:41:13 -0700116 * KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700117 * keyPairGenerator.initialize(
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700118 * new KeyGenParameterSpec.Builder(
119 * "key1",
Alex Klyubin72245d72015-08-11 06:41:13 -0700120 * KeyProperties.PURPOSE_SIGN)
121 * .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700122 * .setDigests(KeyProperties.DIGEST_SHA256,
123 * KeyProperties.DIGEST_SHA384,
124 * KeyProperties.DIGEST_SHA512)
Alex Klyubin72245d72015-08-11 06:41:13 -0700125 * // Only permit the private key to be used if the user authenticated
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700126 * // within the last five minutes.
127 * .setUserAuthenticationRequired(true)
128 * .setUserAuthenticationValidityDurationSeconds(5 * 60)
129 * .build());
130 * KeyPair keyPair = keyPairGenerator.generateKeyPair();
Alex Klyubin72245d72015-08-11 06:41:13 -0700131 * Signature signature = Signature.getInstance("SHA256withECDSA");
132 * signature.initSign(keyPair.getPrivate());
133 * ...
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700134 *
135 * // The key pair can also be obtained from the Android Keystore any time as follows:
136 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
137 * keyStore.load(null);
138 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
139 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
140 * }</pre>
141 *
Alex Klyubin72245d72015-08-11 06:41:13 -0700142 * <p><h3>Example: RSA key pair for signing/verification using RSA-PSS</h3>
143 * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
144 * alias {@code key1} authorized to be used only for signing using the RSA-PSS signature padding
Trevor Johns682c24e2016-04-12 10:13:47 -0700145 * scheme with SHA-256 or SHA-512 digests. The use of the public key is unrestricted.
Alex Klyubin72245d72015-08-11 06:41:13 -0700146 * <pre> {@code
147 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
148 * KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
149 * keyPairGenerator.initialize(
150 * new KeyGenParameterSpec.Builder(
151 * "key1",
152 * KeyProperties.PURPOSE_SIGN)
153 * .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
154 * .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
155 * .build());
156 * KeyPair keyPair = keyPairGenerator.generateKeyPair();
157 * Signature signature = Signature.getInstance("SHA256withRSA/PSS");
158 * signature.initSign(keyPair.getPrivate());
159 * ...
160 *
161 * // The key pair can also be obtained from the Android Keystore any time as follows:
162 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
163 * keyStore.load(null);
164 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
165 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
166 * }</pre>
167 *
168 * <p><h3>Example: RSA key pair for encryption/decryption using RSA OAEP</h3>
169 * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
170 * alias {@code key1} where the private key is authorized to be used only for decryption using RSA
Trevor Johns682c24e2016-04-12 10:13:47 -0700171 * OAEP encryption padding scheme with SHA-256 or SHA-512 digests. The use of the public key is
172 * unrestricted.
Alex Klyubin72245d72015-08-11 06:41:13 -0700173 * <pre> {@code
174 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
175 * KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
176 * keyPairGenerator.initialize(
177 * new KeyGenParameterSpec.Builder(
178 * "key1",
179 * KeyProperties.PURPOSE_DECRYPT)
180 * .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
181 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
182 * .build());
183 * KeyPair keyPair = keyPairGenerator.generateKeyPair();
184 * Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
185 * cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
186 * ...
187 *
188 * // The key pair can also be obtained from the Android Keystore any time as follows:
189 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
190 * keyStore.load(null);
191 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
192 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
193 * }</pre>
194 *
195 * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700196 * The following example illustrates how to generate an AES key in the Android KeyStore system under
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700197 * alias {@code key2} authorized to be used only for encryption/decryption in GCM mode with no
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700198 * padding.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700199 * <pre> {@code
200 * KeyGenerator keyGenerator = KeyGenerator.getInstance(
Alex Klyubin72245d72015-08-11 06:41:13 -0700201 * KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
Kevin Hufnagle8cc88982017-11-29 12:06:52 -0800202 * keyGenerator.init(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700203 * new KeyGenParameterSpec.Builder("key2",
204 * KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700205 * .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
206 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700207 * .build());
208 * SecretKey key = keyGenerator.generateKey();
209 *
Alex Klyubin72245d72015-08-11 06:41:13 -0700210 * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
211 * cipher.init(Cipher.ENCRYPT_MODE, key);
212 * ...
213 *
214 * // The key can also be obtained from the Android Keystore any time as follows:
215 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
216 * keyStore.load(null);
217 * key = (SecretKey) keyStore.getKey("key2", null);
218 * }</pre>
219 *
220 * <p><h3>Example: HMAC key for generating a MAC using SHA-256</h3>
221 * This example illustrates how to generate an HMAC key in the Android KeyStore system under alias
222 * {@code key2} authorized to be used only for generating an HMAC using SHA-256.
223 * <pre> {@code
224 * KeyGenerator keyGenerator = KeyGenerator.getInstance(
225 * KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
Kevin Hufnagle8cc88982017-11-29 12:06:52 -0800226 * keyGenerator.init(
Alex Klyubin72245d72015-08-11 06:41:13 -0700227 * new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build());
228 * SecretKey key = keyGenerator.generateKey();
229 * Mac mac = Mac.getInstance("HmacSHA256");
230 * mac.init(key);
231 * ...
232 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700233 * // The key can also be obtained from the Android Keystore any time as follows:
234 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
235 * keyStore.load(null);
236 * key = (SecretKey) keyStore.getKey("key2", null);
237 * }</pre>
238 */
Brian Young5437b812018-02-23 18:04:20 +0000239public final class KeyGenParameterSpec implements AlgorithmParameterSpec, UserAuthArgs {
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700240
241 private static final X500Principal DEFAULT_CERT_SUBJECT = new X500Principal("CN=fake");
242 private static final BigInteger DEFAULT_CERT_SERIAL_NUMBER = new BigInteger("1");
243 private static final Date DEFAULT_CERT_NOT_BEFORE = new Date(0L); // Jan 1 1970
244 private static final Date DEFAULT_CERT_NOT_AFTER = new Date(2461449600000L); // Jan 1 2048
245
246 private final String mKeystoreAlias;
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700247 private final int mUid;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700248 private final int mKeySize;
249 private final AlgorithmParameterSpec mSpec;
250 private final X500Principal mCertificateSubject;
251 private final BigInteger mCertificateSerialNumber;
252 private final Date mCertificateNotBefore;
253 private final Date mCertificateNotAfter;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700254 private final Date mKeyValidityStart;
255 private final Date mKeyValidityForOriginationEnd;
256 private final Date mKeyValidityForConsumptionEnd;
257 private final @KeyProperties.PurposeEnum int mPurposes;
258 private final @KeyProperties.DigestEnum String[] mDigests;
259 private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
260 private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
261 private final @KeyProperties.BlockModeEnum String[] mBlockModes;
262 private final boolean mRandomizedEncryptionRequired;
263 private final boolean mUserAuthenticationRequired;
264 private final int mUserAuthenticationValidityDurationSeconds;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600265 private final boolean mUserPresenceRequired;
Shawn Willden8d8c7472016-02-02 08:27:39 -0700266 private final byte[] mAttestationChallenge;
267 private final boolean mUniqueIdIncluded;
Shawn Willdenadef4962016-01-29 07:07:16 -0700268 private final boolean mUserAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000269 private final boolean mInvalidatedByBiometricEnrollment;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800270 private final boolean mIsStrongBoxBacked;
David Zeuthena8e8b652017-10-25 14:25:55 -0400271 private final boolean mUserConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000272 private final boolean mUnlockedDeviceRequired;
Eran Messeri5a5c6e02018-06-28 11:20:44 +0100273 /*
274 * ***NOTE***: All new fields MUST also be added to the following:
275 * ParcelableKeyGenParameterSpec class.
276 * The KeyGenParameterSpec.Builder constructor that takes a KeyGenParameterSpec
277 */
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700278
279 /**
280 * @hide should be built with Builder
281 */
282 public KeyGenParameterSpec(
283 String keyStoreAlias,
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700284 int uid,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700285 int keySize,
286 AlgorithmParameterSpec spec,
287 X500Principal certificateSubject,
288 BigInteger certificateSerialNumber,
289 Date certificateNotBefore,
290 Date certificateNotAfter,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700291 Date keyValidityStart,
292 Date keyValidityForOriginationEnd,
293 Date keyValidityForConsumptionEnd,
294 @KeyProperties.PurposeEnum int purposes,
295 @KeyProperties.DigestEnum String[] digests,
296 @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
297 @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
298 @KeyProperties.BlockModeEnum String[] blockModes,
299 boolean randomizedEncryptionRequired,
300 boolean userAuthenticationRequired,
Shawn Willden8d8c7472016-02-02 08:27:39 -0700301 int userAuthenticationValidityDurationSeconds,
Shawn Willden3c1830b2018-03-27 16:10:37 -0600302 boolean userPresenceRequired,
Shawn Willden8d8c7472016-02-02 08:27:39 -0700303 byte[] attestationChallenge,
Shawn Willdenadef4962016-01-29 07:07:16 -0700304 boolean uniqueIdIncluded,
Shawn Willdenc38eae52016-02-22 23:28:34 +0000305 boolean userAuthenticationValidWhileOnBody,
Frank Salim21d9c1d2017-12-19 22:38:09 -0800306 boolean invalidatedByBiometricEnrollment,
David Zeuthena8e8b652017-10-25 14:25:55 -0400307 boolean isStrongBoxBacked,
Brian Young36716eb2018-02-23 18:04:20 +0000308 boolean userConfirmationRequired,
309 boolean unlockedDeviceRequired) {
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700310 if (TextUtils.isEmpty(keyStoreAlias)) {
311 throw new IllegalArgumentException("keyStoreAlias must not be empty");
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700312 }
313
314 if (certificateSubject == null) {
315 certificateSubject = DEFAULT_CERT_SUBJECT;
316 }
317 if (certificateNotBefore == null) {
318 certificateNotBefore = DEFAULT_CERT_NOT_BEFORE;
319 }
320 if (certificateNotAfter == null) {
321 certificateNotAfter = DEFAULT_CERT_NOT_AFTER;
322 }
323 if (certificateSerialNumber == null) {
324 certificateSerialNumber = DEFAULT_CERT_SERIAL_NUMBER;
325 }
326
327 if (certificateNotAfter.before(certificateNotBefore)) {
328 throw new IllegalArgumentException("certificateNotAfter < certificateNotBefore");
329 }
330
331 mKeystoreAlias = keyStoreAlias;
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700332 mUid = uid;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700333 mKeySize = keySize;
334 mSpec = spec;
335 mCertificateSubject = certificateSubject;
336 mCertificateSerialNumber = certificateSerialNumber;
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700337 mCertificateNotBefore = Utils.cloneIfNotNull(certificateNotBefore);
338 mCertificateNotAfter = Utils.cloneIfNotNull(certificateNotAfter);
339 mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
340 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
341 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700342 mPurposes = purposes;
343 mDigests = ArrayUtils.cloneIfNotEmpty(digests);
344 mEncryptionPaddings =
345 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
346 mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
347 mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
348 mRandomizedEncryptionRequired = randomizedEncryptionRequired;
349 mUserAuthenticationRequired = userAuthenticationRequired;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600350 mUserPresenceRequired = userPresenceRequired;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700351 mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
Shawn Willden8d8c7472016-02-02 08:27:39 -0700352 mAttestationChallenge = Utils.cloneIfNotNull(attestationChallenge);
353 mUniqueIdIncluded = uniqueIdIncluded;
Shawn Willdenadef4962016-01-29 07:07:16 -0700354 mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000355 mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800356 mIsStrongBoxBacked = isStrongBoxBacked;
David Zeuthena8e8b652017-10-25 14:25:55 -0400357 mUserConfirmationRequired = userConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000358 mUnlockedDeviceRequired = unlockedDeviceRequired;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700359 }
360
361 /**
362 * Returns the alias that will be used in the {@code java.security.KeyStore}
363 * in conjunction with the {@code AndroidKeyStore}.
364 */
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700365 @NonNull
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700366 public String getKeystoreAlias() {
367 return mKeystoreAlias;
368 }
369
370 /**
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700371 * Returns the UID which will own the key. {@code -1} is an alias for the UID of the current
372 * process.
373 *
374 * @hide
375 */
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100376 @UnsupportedAppUsage
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700377 public int getUid() {
378 return mUid;
379 }
380
381 /**
Alex Klyubin3ceb1a02015-06-05 15:51:06 -0700382 * Returns the requested key size. If {@code -1}, the size should be looked up from
383 * {@link #getAlgorithmParameterSpec()}, if provided, otherwise an algorithm-specific default
384 * size should be used.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700385 */
386 public int getKeySize() {
387 return mKeySize;
388 }
389
390 /**
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700391 * Returns the key algorithm-specific {@link AlgorithmParameterSpec} that will be used for
392 * creation of the key or {@code null} if algorithm-specific defaults should be used.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700393 */
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700394 @Nullable
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700395 public AlgorithmParameterSpec getAlgorithmParameterSpec() {
396 return mSpec;
397 }
398
399 /**
400 * Returns the subject distinguished name to be used on the X.509 certificate that will be put
401 * in the {@link java.security.KeyStore}.
402 */
403 @NonNull
404 public X500Principal getCertificateSubject() {
405 return mCertificateSubject;
406 }
407
408 /**
409 * Returns the serial number to be used on the X.509 certificate that will be put in the
410 * {@link java.security.KeyStore}.
411 */
412 @NonNull
413 public BigInteger getCertificateSerialNumber() {
414 return mCertificateSerialNumber;
415 }
416
417 /**
418 * Returns the start date to be used on the X.509 certificate that will be put in the
419 * {@link java.security.KeyStore}.
420 */
421 @NonNull
422 public Date getCertificateNotBefore() {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700423 return Utils.cloneIfNotNull(mCertificateNotBefore);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700424 }
425
426 /**
427 * Returns the end date to be used on the X.509 certificate that will be put in the
428 * {@link java.security.KeyStore}.
429 */
430 @NonNull
431 public Date getCertificateNotAfter() {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700432 return Utils.cloneIfNotNull(mCertificateNotAfter);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700433 }
434
435 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700436 * Returns the time instant before which the key is not yet valid or {@code null} if not
437 * restricted.
438 */
439 @Nullable
440 public Date getKeyValidityStart() {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700441 return Utils.cloneIfNotNull(mKeyValidityStart);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700442 }
443
444 /**
445 * Returns the time instant after which the key is no longer valid for decryption and
446 * verification or {@code null} if not restricted.
447 */
448 @Nullable
449 public Date getKeyValidityForConsumptionEnd() {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700450 return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700451 }
452
453 /**
454 * Returns the time instant after which the key is no longer valid for encryption and signing
455 * or {@code null} if not restricted.
456 */
457 @Nullable
458 public Date getKeyValidityForOriginationEnd() {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700459 return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700460 }
461
462 /**
463 * Returns the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
464 * Attempts to use the key for any other purpose will be rejected.
465 *
466 * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
467 */
468 public @KeyProperties.PurposeEnum int getPurposes() {
469 return mPurposes;
470 }
471
472 /**
473 * Returns the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384} with which the
474 * key can be used or {@code null} if not specified.
475 *
476 * <p>See {@link KeyProperties}.{@code DIGEST} constants.
477 *
478 * @throws IllegalStateException if this set has not been specified.
479 *
480 * @see #isDigestsSpecified()
481 */
482 @NonNull
483 public @KeyProperties.DigestEnum String[] getDigests() {
484 if (mDigests == null) {
485 throw new IllegalStateException("Digests not specified");
486 }
487 return ArrayUtils.cloneIfNotEmpty(mDigests);
488 }
489
490 /**
491 * Returns {@code true} if the set of digest algorithms with which the key can be used has been
492 * specified.
493 *
494 * @see #getDigests()
495 */
496 @NonNull
497 public boolean isDigestsSpecified() {
498 return mDigests != null;
499 }
500
501 /**
502 * Returns the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OEAPPadding},
503 * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
504 * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
505 * rejected.
506 *
507 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
508 */
509 @NonNull
510 public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
511 return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
512 }
513
514 /**
515 * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
516 * can be used when signing/verifying. Attempts to use the key with any other padding scheme
517 * will be rejected.
518 *
519 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
520 */
521 @NonNull
522 public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
523 return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
524 }
525
526 /**
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700527 * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700528 * when encrypting/decrypting. Attempts to use the key with any other block modes will be
529 * rejected.
530 *
531 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
532 */
533 @NonNull
534 public @KeyProperties.BlockModeEnum String[] getBlockModes() {
535 return ArrayUtils.cloneIfNotEmpty(mBlockModes);
536 }
537
538 /**
539 * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
540 * different ciphertexts for the same plaintext every time. The formal cryptographic property
541 * being required is <em>indistinguishability under chosen-plaintext attack ({@code
542 * IND-CPA})</em>. This property is important because it mitigates several classes of
543 * weaknesses due to which ciphertext may leak information about plaintext. For example, if a
544 * given plaintext always produces the same ciphertext, an attacker may see the repeated
545 * ciphertexts and be able to deduce something about the plaintext.
546 */
547 public boolean isRandomizedEncryptionRequired() {
548 return mRandomizedEncryptionRequired;
549 }
550
551 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700552 * Returns {@code true} if the key is authorized to be used only if the user has been
553 * authenticated.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700554 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700555 * <p>This authorization applies only to secret key and private key operations. Public key
556 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700557 *
558 * @see #getUserAuthenticationValidityDurationSeconds()
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700559 * @see Builder#setUserAuthenticationRequired(boolean)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700560 */
561 public boolean isUserAuthenticationRequired() {
562 return mUserAuthenticationRequired;
563 }
564
565 /**
David Zeuthena8e8b652017-10-25 14:25:55 -0400566 * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
567 * user.
568 *
569 * Confirmation is separate from user authentication (see
570 * {@link Builder#setUserAuthenticationRequired(boolean)}). Keys can be created that require
571 * confirmation but not user authentication, or user authentication but not confirmation, or
572 * both. Confirmation verifies that some user with physical possession of the device has
573 * approved a displayed message. User authentication verifies that the correct user is present
574 * and has authenticated.
575 *
576 * <p>This authorization applies only to secret key and private key operations. Public key
577 * operations are not restricted.
578 *
579 * @see Builder#setUserConfirmationRequired(boolean)
580 */
581 public boolean isUserConfirmationRequired() {
582 return mUserConfirmationRequired;
583 }
584
585 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700586 * Gets the duration of time (seconds) for which this key is authorized to be used after the
587 * user is successfully authenticated. This has effect only if user authentication is required
588 * (see {@link #isUserAuthenticationRequired()}).
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700589 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700590 * <p>This authorization applies only to secret key and private key operations. Public key
591 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700592 *
593 * @return duration in seconds or {@code -1} if authentication is required for every use of the
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700594 * key.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700595 *
596 * @see #isUserAuthenticationRequired()
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700597 * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700598 */
599 public int getUserAuthenticationValidityDurationSeconds() {
600 return mUserAuthenticationValidityDurationSeconds;
601 }
602
603 /**
Allen Webbfcd05a92018-01-18 08:34:45 -0800604 * Returns {@code true} if the key is authorized to be used only if a test of user presence has
605 * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls.
Allen Webb9b5853d2018-04-10 10:33:42 -0700606 * It requires that the KeyStore implementation have a direct way to validate the user presence
607 * for example a KeyStore hardware backed strongbox can use a button press that is observable
608 * in hardware. A test for user presence is tangential to authentication. The test can be part
609 * of an authentication step as long as this step can be validated by the hardware protecting
610 * the key and cannot be spoofed. For example, a physical button press can be used as a test of
611 * user presence if the other pins connected to the button are not able to simulate a button
612 * press. There must be no way for the primary processor to fake a button press, or that
613 * button must not be used as a test of user presence.
Allen Webbfcd05a92018-01-18 08:34:45 -0800614 */
Shawn Willden3c1830b2018-03-27 16:10:37 -0600615 public boolean isUserPresenceRequired() {
616 return mUserPresenceRequired;
Allen Webbfcd05a92018-01-18 08:34:45 -0800617 }
618
619 /**
Shawn Willden8d8c7472016-02-02 08:27:39 -0700620 * Returns the attestation challenge value that will be placed in attestation certificate for
621 * this key pair.
622 *
623 * <p>If this method returns non-{@code null}, the public key certificate for this key pair will
624 * contain an extension that describes the details of the key's configuration and
625 * authorizations, including the content of the attestation challenge value. If the key is in
626 * secure hardware, and if the secure hardware supports attestation, the certificate will be
627 * signed by a chain of certificates rooted at a trustworthy CA key. Otherwise the chain will
628 * be rooted at an untrusted certificate.
629 *
630 * <p>If this method returns {@code null}, and the spec is used to generate an asymmetric (RSA
631 * or EC) key pair, the public key will have a self-signed certificate if it has purpose {@link
Shawn Willden9739d482016-07-21 10:02:16 -0600632 * KeyProperties#PURPOSE_SIGN}. If does not have purpose {@link KeyProperties#PURPOSE_SIGN}, it
633 * will have a fake certificate.
Shawn Willden8d8c7472016-02-02 08:27:39 -0700634 *
635 * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
Shawn Willden9739d482016-07-21 10:02:16 -0600636 * KeyGenParameterSpec with getAttestationChallenge returning non-null is used to generate a
637 * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
Shawn Willden8d8c7472016-02-02 08:27:39 -0700638 * {@link java.security.InvalidAlgorithmParameterException}.
639 *
640 * @see Builder#setAttestationChallenge(byte[])
641 */
Shawn Willden8d8c7472016-02-02 08:27:39 -0700642 public byte[] getAttestationChallenge() {
643 return Utils.cloneIfNotNull(mAttestationChallenge);
644 }
645
646 /**
647 * @hide This is a system-only API
648 *
649 * Returns {@code true} if the attestation certificate will contain a unique ID field.
650 */
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100651 @UnsupportedAppUsage
Shawn Willden8d8c7472016-02-02 08:27:39 -0700652 public boolean isUniqueIdIncluded() {
653 return mUniqueIdIncluded;
654 }
655
656 /**
Shawn Willden26e8d552016-06-14 17:27:10 -0600657 * Returns {@code true} if the key will remain authorized only until the device is removed from
658 * the user's body, up to the validity duration. This option has no effect on keys that don't
659 * have an authentication validity duration, and has no effect if the device lacks an on-body
660 * sensor.
Shawn Willdenadef4962016-01-29 07:07:16 -0700661 *
662 * <p>Authorization applies only to secret key and private key operations. Public key operations
663 * are not restricted.
664 *
665 * @see #isUserAuthenticationRequired()
666 * @see #getUserAuthenticationValidityDurationSeconds()
667 * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
668 */
669 public boolean isUserAuthenticationValidWhileOnBody() {
670 return mUserAuthenticationValidWhileOnBody;
671 }
672
673 /**
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700674 * Returns {@code true} if the key is irreversibly invalidated when a new biometric is
675 * enrolled or all enrolled biometrics are removed. This has effect only for keys that
676 * require biometric user authentication for every use.
Shawn Willdenc38eae52016-02-22 23:28:34 +0000677 *
678 * @see #isUserAuthenticationRequired()
679 * @see #getUserAuthenticationValidityDurationSeconds()
680 * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
681 */
682 public boolean isInvalidatedByBiometricEnrollment() {
683 return mInvalidatedByBiometricEnrollment;
684 }
685
686 /**
Frank Salim21d9c1d2017-12-19 22:38:09 -0800687 * Returns {@code true} if the key is protected by a Strongbox security chip.
688 */
689 public boolean isStrongBoxBacked() {
690 return mIsStrongBoxBacked;
691 }
692
693 /**
Brian C. Young1c5ee612018-04-10 08:43:53 -0700694 * Returns {@code true} if the screen must be unlocked for this key to be used for decryption or
695 * signing. Encryption and signature verification will still be available when the screen is
Brian C. Young6f8fa9a2018-04-02 12:40:58 -0700696 * locked.
Brian Young36716eb2018-02-23 18:04:20 +0000697 *
698 * @see Builder#setUnlockedDeviceRequired(boolean)
699 */
700 public boolean isUnlockedDeviceRequired() {
701 return mUnlockedDeviceRequired;
702 }
703
704 /**
Brian Young5437b812018-02-23 18:04:20 +0000705 * @hide
706 */
707 public long getBoundToSpecificSecureUserId() {
708 return GateKeeper.INVALID_SECURE_USER_ID;
709 }
710
711 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700712 * Builder of {@link KeyGenParameterSpec} instances.
713 */
714 public final static class Builder {
715 private final String mKeystoreAlias;
716 private @KeyProperties.PurposeEnum int mPurposes;
717
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700718 private int mUid = KeyStore.UID_SELF;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700719 private int mKeySize = -1;
720 private AlgorithmParameterSpec mSpec;
721 private X500Principal mCertificateSubject;
722 private BigInteger mCertificateSerialNumber;
723 private Date mCertificateNotBefore;
724 private Date mCertificateNotAfter;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700725 private Date mKeyValidityStart;
726 private Date mKeyValidityForOriginationEnd;
727 private Date mKeyValidityForConsumptionEnd;
728 private @KeyProperties.DigestEnum String[] mDigests;
729 private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
730 private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
731 private @KeyProperties.BlockModeEnum String[] mBlockModes;
732 private boolean mRandomizedEncryptionRequired = true;
733 private boolean mUserAuthenticationRequired;
734 private int mUserAuthenticationValidityDurationSeconds = -1;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600735 private boolean mUserPresenceRequired = false;
Shawn Willden8d8c7472016-02-02 08:27:39 -0700736 private byte[] mAttestationChallenge = null;
737 private boolean mUniqueIdIncluded = false;
Shawn Willdenadef4962016-01-29 07:07:16 -0700738 private boolean mUserAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000739 private boolean mInvalidatedByBiometricEnrollment = true;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800740 private boolean mIsStrongBoxBacked = false;
David Zeuthena8e8b652017-10-25 14:25:55 -0400741 private boolean mUserConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000742 private boolean mUnlockedDeviceRequired = false;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700743
744 /**
745 * Creates a new instance of the {@code Builder}.
746 *
747 * @param keystoreAlias alias of the entry in which the generated key will appear in
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700748 * Android KeyStore. Must not be empty.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700749 * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
750 * used. Attempts to use the key for any other purpose will be rejected.
751 *
752 * <p>If the set of purposes for which the key can be used does not contain
753 * {@link KeyProperties#PURPOSE_SIGN}, the self-signed certificate generated by
754 * {@link KeyPairGenerator} of {@code AndroidKeyStore} provider will contain an
755 * invalid signature. This is OK if the certificate is only used for obtaining the
756 * public key from Android KeyStore.
757 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700758 * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
759 */
760 public Builder(@NonNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes) {
761 if (keystoreAlias == null) {
762 throw new NullPointerException("keystoreAlias == null");
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700763 } else if (keystoreAlias.isEmpty()) {
764 throw new IllegalArgumentException("keystoreAlias must not be empty");
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700765 }
766 mKeystoreAlias = keystoreAlias;
767 mPurposes = purposes;
768 }
769
770 /**
Eran Messeria1730642017-12-11 17:48:47 +0000771 * A Builder constructor taking in an already-built KeyGenParameterSpec, useful for
772 * changing values of the KeyGenParameterSpec quickly.
773 * @hide Should be used internally only.
774 */
775 public Builder(@NonNull KeyGenParameterSpec sourceSpec) {
776 this(sourceSpec.getKeystoreAlias(), sourceSpec.getPurposes());
777 mUid = sourceSpec.getUid();
778 mKeySize = sourceSpec.getKeySize();
779 mSpec = sourceSpec.getAlgorithmParameterSpec();
780 mCertificateSubject = sourceSpec.getCertificateSubject();
781 mCertificateSerialNumber = sourceSpec.getCertificateSerialNumber();
782 mCertificateNotBefore = sourceSpec.getCertificateNotBefore();
783 mCertificateNotAfter = sourceSpec.getCertificateNotAfter();
784 mKeyValidityStart = sourceSpec.getKeyValidityStart();
785 mKeyValidityForOriginationEnd = sourceSpec.getKeyValidityForOriginationEnd();
786 mKeyValidityForConsumptionEnd = sourceSpec.getKeyValidityForConsumptionEnd();
787 mPurposes = sourceSpec.getPurposes();
788 if (sourceSpec.isDigestsSpecified()) {
789 mDigests = sourceSpec.getDigests();
790 }
791 mEncryptionPaddings = sourceSpec.getEncryptionPaddings();
792 mSignaturePaddings = sourceSpec.getSignaturePaddings();
793 mBlockModes = sourceSpec.getBlockModes();
794 mRandomizedEncryptionRequired = sourceSpec.isRandomizedEncryptionRequired();
795 mUserAuthenticationRequired = sourceSpec.isUserAuthenticationRequired();
796 mUserAuthenticationValidityDurationSeconds =
797 sourceSpec.getUserAuthenticationValidityDurationSeconds();
Shawn Willden3c1830b2018-03-27 16:10:37 -0600798 mUserPresenceRequired = sourceSpec.isUserPresenceRequired();
Eran Messeria1730642017-12-11 17:48:47 +0000799 mAttestationChallenge = sourceSpec.getAttestationChallenge();
800 mUniqueIdIncluded = sourceSpec.isUniqueIdIncluded();
801 mUserAuthenticationValidWhileOnBody = sourceSpec.isUserAuthenticationValidWhileOnBody();
802 mInvalidatedByBiometricEnrollment = sourceSpec.isInvalidatedByBiometricEnrollment();
Eran Messeri5a5c6e02018-06-28 11:20:44 +0100803 mIsStrongBoxBacked = sourceSpec.isStrongBoxBacked();
804 mUserConfirmationRequired = sourceSpec.isUserConfirmationRequired();
805 mUnlockedDeviceRequired = sourceSpec.isUnlockedDeviceRequired();
Eran Messeria1730642017-12-11 17:48:47 +0000806 }
807
808 /**
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700809 * Sets the UID which will own the key.
810 *
811 * @param uid UID or {@code -1} for the UID of the current process.
812 *
813 * @hide
814 */
815 @NonNull
816 public Builder setUid(int uid) {
817 mUid = uid;
818 return this;
819 }
820
821 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700822 * Sets the size (in bits) of the key to be generated. For instance, for RSA keys this sets
823 * the modulus size, for EC keys this selects a curve with a matching field size, and for
824 * symmetric keys this sets the size of the bitstring which is their key material.
825 *
Alex Klyubin3ceb1a02015-06-05 15:51:06 -0700826 * <p>The default key size is specific to each key algorithm. If key size is not set
827 * via this method, it should be looked up from the algorithm-specific parameters (if any)
828 * provided via
829 * {@link #setAlgorithmParameterSpec(AlgorithmParameterSpec) setAlgorithmParameterSpec}.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700830 */
831 @NonNull
832 public Builder setKeySize(int keySize) {
833 if (keySize < 0) {
834 throw new IllegalArgumentException("keySize < 0");
835 }
836 mKeySize = keySize;
837 return this;
838 }
839
840 /**
841 * Sets the algorithm-specific key generation parameters. For example, for RSA keys this may
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700842 * be an instance of {@link java.security.spec.RSAKeyGenParameterSpec} whereas for EC keys
843 * this may be an instance of {@link java.security.spec.ECGenParameterSpec}.
844 *
845 * <p>These key generation parameters must match other explicitly set parameters (if any),
846 * such as key size.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700847 */
848 public Builder setAlgorithmParameterSpec(@NonNull AlgorithmParameterSpec spec) {
849 if (spec == null) {
850 throw new NullPointerException("spec == null");
851 }
852 mSpec = spec;
853 return this;
854 }
855
856 /**
857 * Sets the subject used for the self-signed certificate of the generated key pair.
858 *
859 * <p>By default, the subject is {@code CN=fake}.
860 */
861 @NonNull
862 public Builder setCertificateSubject(@NonNull X500Principal subject) {
863 if (subject == null) {
864 throw new NullPointerException("subject == null");
865 }
866 mCertificateSubject = subject;
867 return this;
868 }
869
870 /**
871 * Sets the serial number used for the self-signed certificate of the generated key pair.
872 *
873 * <p>By default, the serial number is {@code 1}.
874 */
875 @NonNull
876 public Builder setCertificateSerialNumber(@NonNull BigInteger serialNumber) {
877 if (serialNumber == null) {
878 throw new NullPointerException("serialNumber == null");
879 }
880 mCertificateSerialNumber = serialNumber;
881 return this;
882 }
883
884 /**
885 * Sets the start of the validity period for the self-signed certificate of the generated
886 * key pair.
887 *
888 * <p>By default, this date is {@code Jan 1 1970}.
889 */
890 @NonNull
891 public Builder setCertificateNotBefore(@NonNull Date date) {
892 if (date == null) {
893 throw new NullPointerException("date == null");
894 }
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700895 mCertificateNotBefore = Utils.cloneIfNotNull(date);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700896 return this;
897 }
898
899 /**
900 * Sets the end of the validity period for the self-signed certificate of the generated key
901 * pair.
902 *
903 * <p>By default, this date is {@code Jan 1 2048}.
904 */
905 @NonNull
906 public Builder setCertificateNotAfter(@NonNull Date date) {
907 if (date == null) {
908 throw new NullPointerException("date == null");
909 }
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700910 mCertificateNotAfter = Utils.cloneIfNotNull(date);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700911 return this;
912 }
913
914 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700915 * Sets the time instant before which the key is not yet valid.
916 *
917 * <p>By default, the key is valid at any instant.
918 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700919 * @see #setKeyValidityEnd(Date)
920 */
921 @NonNull
922 public Builder setKeyValidityStart(Date startDate) {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700923 mKeyValidityStart = Utils.cloneIfNotNull(startDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700924 return this;
925 }
926
927 /**
928 * Sets the time instant after which the key is no longer valid.
929 *
930 * <p>By default, the key is valid at any instant.
931 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700932 * @see #setKeyValidityStart(Date)
933 * @see #setKeyValidityForConsumptionEnd(Date)
934 * @see #setKeyValidityForOriginationEnd(Date)
935 */
936 @NonNull
937 public Builder setKeyValidityEnd(Date endDate) {
938 setKeyValidityForOriginationEnd(endDate);
939 setKeyValidityForConsumptionEnd(endDate);
940 return this;
941 }
942
943 /**
944 * Sets the time instant after which the key is no longer valid for encryption and signing.
945 *
946 * <p>By default, the key is valid at any instant.
947 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700948 * @see #setKeyValidityForConsumptionEnd(Date)
949 */
950 @NonNull
951 public Builder setKeyValidityForOriginationEnd(Date endDate) {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700952 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700953 return this;
954 }
955
956 /**
957 * Sets the time instant after which the key is no longer valid for decryption and
958 * verification.
959 *
960 * <p>By default, the key is valid at any instant.
961 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700962 * @see #setKeyValidityForOriginationEnd(Date)
963 */
964 @NonNull
965 public Builder setKeyValidityForConsumptionEnd(Date endDate) {
Alex Klyubin1b937ee2015-06-16 09:51:20 -0700966 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700967 return this;
968 }
969
970 /**
971 * Sets the set of digests algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which
Alex Klyubin38677092015-06-22 13:42:46 -0700972 * the key can be used. Attempts to use the key with any other digest algorithm will be
973 * rejected.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700974 *
Alex Klyubin38677092015-06-22 13:42:46 -0700975 * <p>This must be specified for signing/verification keys and RSA encryption/decryption
976 * keys used with RSA OAEP padding scheme because these operations involve a digest. For
977 * HMAC keys, the default is the digest associated with the key algorithm (e.g.,
Alex Klyubinc58153b2015-07-08 09:31:23 -0700978 * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
979 * for more than one digest.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700980 *
Alex Klyubindcf3d352015-06-11 14:44:46 -0700981 * <p>For private keys used for TLS/SSL client or server authentication it is usually
982 * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
983 * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
984 * a private key to sign it.
985 *
986 * <p>See {@link KeyProperties}.{@code DIGEST} constants.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700987 */
988 @NonNull
989 public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
990 mDigests = ArrayUtils.cloneIfNotEmpty(digests);
991 return this;
992 }
993
994 /**
995 * Sets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OAEPPadding},
996 * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
997 * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
998 * rejected.
999 *
1000 * <p>This must be specified for keys which are used for encryption/decryption.
1001 *
Alex Klyubindcf3d352015-06-11 14:44:46 -07001002 * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
1003 * is usually necessary to authorize the use of no/any padding
Alex Klyubine4928a22015-07-21 13:38:48 -07001004 * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
1005 * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
Alex Klyubindcf3d352015-06-11 14:44:46 -07001006 * required by some cipher suites, and some stacks request decryption using no padding
1007 * whereas others request PKCS#1 padding.
1008 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001009 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
1010 */
1011 @NonNull
1012 public Builder setEncryptionPaddings(
1013 @KeyProperties.EncryptionPaddingEnum String... paddings) {
1014 mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
1015 return this;
1016 }
1017
1018 /**
1019 * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
1020 * can be used when signing/verifying. Attempts to use the key with any other padding scheme
1021 * will be rejected.
1022 *
1023 * <p>This must be specified for RSA keys which are used for signing/verification.
1024 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001025 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
1026 */
1027 @NonNull
1028 public Builder setSignaturePaddings(
1029 @KeyProperties.SignaturePaddingEnum String... paddings) {
1030 mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
1031 return this;
1032 }
1033
1034 /**
Alex Klyubina5e21f0e2015-06-17 11:24:45 -07001035 * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
1036 * used when encrypting/decrypting. Attempts to use the key with any other block modes will
1037 * be rejected.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001038 *
Alex Klyubina5e21f0e2015-06-17 11:24:45 -07001039 * <p>This must be specified for symmetric encryption/decryption keys.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001040 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001041 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
1042 */
1043 @NonNull
1044 public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
1045 mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
1046 return this;
1047 }
1048
1049 /**
1050 * Sets whether encryption using this key must be sufficiently randomized to produce
1051 * different ciphertexts for the same plaintext every time. The formal cryptographic
1052 * property being required is <em>indistinguishability under chosen-plaintext attack
1053 * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
1054 * of weaknesses due to which ciphertext may leak information about plaintext. For example,
1055 * if a given plaintext always produces the same ciphertext, an attacker may see the
1056 * repeated ciphertexts and be able to deduce something about the plaintext.
1057 *
1058 * <p>By default, {@code IND-CPA} is required.
1059 *
1060 * <p>When {@code IND-CPA} is required:
1061 * <ul>
1062 * <li>encryption/decryption transformation which do not offer {@code IND-CPA}, such as
1063 * {@code ECB} with a symmetric encryption algorithm, or RSA encryption/decryption without
1064 * padding, are prohibited;</li>
Alex Klyubina5e21f0e2015-06-17 11:24:45 -07001065 * <li>in block modes which use an IV, such as {@code GCM}, {@code CBC}, and {@code CTR},
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001066 * caller-provided IVs are rejected when encrypting, to ensure that only random IVs are
1067 * used.</li>
1068 * </ul>
1069 *
1070 * <p>Before disabling this requirement, consider the following approaches instead:
1071 * <ul>
1072 * <li>If you are generating a random IV for encryption and then initializing a {@code}
1073 * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
1074 * instead. This will occur if the {@code Cipher} is initialized for encryption without an
1075 * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
1076 * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
1077 * random, such as the name of the file being encrypted, or transaction ID, or password,
1078 * or a device identifier), consider changing your design to use a random IV which will then
1079 * be provided in addition to the ciphertext to the entities which need to decrypt the
1080 * ciphertext.</li>
1081 * <li>If you are using RSA encryption without padding, consider switching to encryption
1082 * padding schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
1083 * </ul>
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001084 */
1085 @NonNull
1086 public Builder setRandomizedEncryptionRequired(boolean required) {
1087 mRandomizedEncryptionRequired = required;
1088 return this;
1089 }
1090
1091 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001092 * Sets whether this key is authorized to be used only if the user has been authenticated.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001093 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001094 * <p>By default, the key is authorized to be used regardless of whether the user has been
1095 * authenticated.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001096 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001097 * <p>When user authentication is required:
1098 * <ul>
1099 * <li>The key can only be generated if secure lock screen is set up (see
1100 * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
1101 * authentication takes place for every use of the key (see
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001102 * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
1103 * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001104 * <li>The use of the key must be authorized by the user by authenticating to this Android
1105 * device using a subset of their secure lock screen credentials such as
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001106 * password/PIN/pattern or biometric.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001107 * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
1108 * information</a>.
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001109 * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
1110 * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
1111 * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
1112 * Additionally, if the key requires that user authentication takes place for every use of
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001113 * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
1114 * no more biometrics are enrolled, unless {@link
Shawn Willdenc38eae52016-02-22 23:28:34 +00001115 * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
1116 * enrollment. Attempts to initialize cryptographic operations using such keys will throw
1117 * {@link KeyPermanentlyInvalidatedException}.</li>
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001118 * </ul>
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001119 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001120 * <p>This authorization applies only to secret key and private key operations. Public key
1121 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001122 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001123 * @see #setUserAuthenticationValidityDurationSeconds(int)
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001124 * @see KeyguardManager#isDeviceSecure()
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001125 * @see BiometricManager#canAuthenticate()
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001126 */
1127 @NonNull
1128 public Builder setUserAuthenticationRequired(boolean required) {
1129 mUserAuthenticationRequired = required;
1130 return this;
1131 }
1132
1133 /**
David Zeuthena8e8b652017-10-25 14:25:55 -04001134 * Sets whether this key is authorized to be used only for messages confirmed by the
1135 * user.
1136 *
1137 * Confirmation is separate from user authentication (see
1138 * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require
1139 * confirmation but not user authentication, or user authentication but not confirmation,
1140 * or both. Confirmation verifies that some user with physical possession of the device has
1141 * approved a displayed message. User authentication verifies that the correct user is
1142 * present and has authenticated.
1143 *
1144 * <p>This authorization applies only to secret key and private key operations. Public key
1145 * operations are not restricted.
1146 *
Aurimas Liutikase701dc12018-06-01 16:04:37 -07001147 * See {@link android.security.ConfirmationPrompt} class for
David Zeuthena8e8b652017-10-25 14:25:55 -04001148 * more details about user confirmations.
1149 */
1150 @NonNull
1151 public Builder setUserConfirmationRequired(boolean required) {
1152 mUserConfirmationRequired = required;
1153 return this;
1154 }
1155
1156 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001157 * Sets the duration of time (seconds) for which this key is authorized to be used after the
1158 * user is successfully authenticated. This has effect if the key requires user
1159 * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001160 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001161 * <p>By default, if user authentication is required, it must take place for every use of
1162 * the key.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001163 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001164 * <p>Cryptographic operations involving keys which require user authentication to take
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001165 * place for every operation can only use biometric authentication. This is achieved by
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001166 * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001167 * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
1168 * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001169 * the cryptographic operation only if the authentication flow succeeds.
1170 *
1171 * <p>Cryptographic operations involving keys which are authorized to be used for a duration
1172 * of time after a successful user authentication event can only use secure lock screen
1173 * authentication. These cryptographic operations will throw
1174 * {@link UserNotAuthenticatedException} during initialization if the user needs to be
1175 * authenticated to proceed. This situation can be resolved by the user unlocking the secure
1176 * lock screen of the Android or by going through the confirm credential flow initiated by
1177 * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
1178 * Once resolved, initializing a new cryptographic operation using this key (or any other
1179 * key which is authorized to be used for a fixed duration of time after user
1180 * authentication) should succeed provided the user authentication flow completed
1181 * successfully.
1182 *
1183 * @param seconds duration in seconds or {@code -1} if user authentication must take place
1184 * for every use of the key.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001185 *
1186 * @see #setUserAuthenticationRequired(boolean)
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001187 * @see BiometricPrompt
1188 * @see BiometricPrompt.CryptoObject
Alex Klyubin83cc7a32015-06-16 10:44:11 -07001189 * @see KeyguardManager
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001190 */
1191 @NonNull
1192 public Builder setUserAuthenticationValidityDurationSeconds(
1193 @IntRange(from = -1) int seconds) {
Alex Klyubin1b937ee2015-06-16 09:51:20 -07001194 if (seconds < -1) {
1195 throw new IllegalArgumentException("seconds must be -1 or larger");
1196 }
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001197 mUserAuthenticationValidityDurationSeconds = seconds;
1198 return this;
1199 }
1200
Shawn Willden8d8c7472016-02-02 08:27:39 -07001201 /**
Allen Webbfcd05a92018-01-18 08:34:45 -08001202 * Sets whether a test of user presence is required to be performed between the
1203 * {@code Signature.initSign()} and {@code Signature.sign()} method calls.
Allen Webb9b5853d2018-04-10 10:33:42 -07001204 * It requires that the KeyStore implementation have a direct way to validate the user
1205 * presence for example a KeyStore hardware backed strongbox can use a button press that
1206 * is observable in hardware. A test for user presence is tangential to authentication. The
1207 * test can be part of an authentication step as long as this step can be validated by the
1208 * hardware protecting the key and cannot be spoofed. For example, a physical button press
1209 * can be used as a test of user presence if the other pins connected to the button are not
1210 * able to simulate a button press.There must be no way for the primary processor to fake a
1211 * button press, or that button must not be used as a test of user presence.
Allen Webbfcd05a92018-01-18 08:34:45 -08001212 */
1213 @NonNull
Shawn Willden3c1830b2018-03-27 16:10:37 -06001214 public Builder setUserPresenceRequired(boolean required) {
1215 mUserPresenceRequired = required;
Allen Webbfcd05a92018-01-18 08:34:45 -08001216 return this;
1217 }
1218
1219 /**
Shawn Willden8d8c7472016-02-02 08:27:39 -07001220 * Sets whether an attestation certificate will be generated for this key pair, and what
1221 * challenge value will be placed in the certificate. The attestation certificate chain
1222 * can be retrieved with with {@link java.security.KeyStore#getCertificateChain(String)}.
1223 *
1224 * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for
1225 * this key pair will contain an extension that describes the details of the key's
1226 * configuration and authorizations, including the {@code attestationChallenge} value. If
1227 * the key is in secure hardware, and if the secure hardware supports attestation, the
1228 * certificate will be signed by a chain of certificates rooted at a trustworthy CA key.
1229 * Otherwise the chain will be rooted at an untrusted certificate.
1230 *
1231 * <p>The purpose of the challenge value is to enable relying parties to verify that the key
1232 * was created in response to a specific request. If attestation is desired but no
1233 * challenged is needed, any non-{@code null} value may be used, including an empty byte
1234 * array.
1235 *
1236 * <p>If {@code attestationChallenge} is {@code null}, and this spec is used to generate an
1237 * asymmetric (RSA or EC) key pair, the public key certificate will be self-signed if the
Shawn Willden9739d482016-07-21 10:02:16 -06001238 * key has purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}. If the key
1239 * does not have purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}, it is
1240 * not possible to use the key to sign a certificate, so the public key certificate will
1241 * contain a dummy signature.
Shawn Willden8d8c7472016-02-02 08:27:39 -07001242 *
1243 * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
Shawn Willden9739d482016-07-21 10:02:16 -06001244 * {@link #getAttestationChallenge()} returns non-null and the spec is used to generate a
1245 * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw
Shawn Willden8d8c7472016-02-02 08:27:39 -07001246 * {@link java.security.InvalidAlgorithmParameterException}.
Shawn Willden8d8c7472016-02-02 08:27:39 -07001247 */
1248 @NonNull
1249 public Builder setAttestationChallenge(byte[] attestationChallenge) {
1250 mAttestationChallenge = attestationChallenge;
1251 return this;
1252 }
1253
1254 /**
1255 * @hide Only system apps can use this method.
1256 *
1257 * Sets whether to include a temporary unique ID field in the attestation certificate.
1258 */
Artur Satayevf0b7d0b2019-11-04 11:16:45 +00001259 @UnsupportedAppUsage
Shawn Willden13e230f2018-04-10 17:21:39 -06001260 @TestApi
Shawn Willden8d8c7472016-02-02 08:27:39 -07001261 @NonNull
1262 public Builder setUniqueIdIncluded(boolean uniqueIdIncluded) {
1263 mUniqueIdIncluded = uniqueIdIncluded;
1264 return this;
1265 }
1266
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001267 /**
Shawn Willden26e8d552016-06-14 17:27:10 -06001268 * Sets whether the key will remain authorized only until the device is removed from the
1269 * user's body up to the limit of the authentication validity period (see
1270 * {@link #setUserAuthenticationValidityDurationSeconds} and
1271 * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
1272 * user's body, the key will be considered unauthorized and the user will need to
1273 * re-authenticate to use it. For keys without an authentication validity period this
1274 * parameter has no effect.
Shawn Willdenadef4962016-01-29 07:07:16 -07001275 *
Shawn Willden26e8d552016-06-14 17:27:10 -06001276 * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
1277 * effect; the device will always be considered to be "on-body" and the key will therefore
1278 * remain authorized until the validity period ends.
Shawn Willdenadef4962016-01-29 07:07:16 -07001279 *
Shawn Willden26e8d552016-06-14 17:27:10 -06001280 * @param remainsValid if {@code true}, and if the device supports on-body detection, key
1281 * will be invalidated when the device is removed from the user's body or when the
1282 * authentication validity expires, whichever occurs first.
Shawn Willdenadef4962016-01-29 07:07:16 -07001283 */
1284 @NonNull
1285 public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
1286 mUserAuthenticationValidWhileOnBody = remainsValid;
1287 return this;
1288 }
1289
1290 /**
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001291 * Sets whether this key should be invalidated on biometric enrollment. This
Shawn Willdenc38eae52016-02-22 23:28:34 +00001292 * applies only to keys which require user authentication (see {@link
1293 * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
1294 * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001295 * valid for biometric authentication only.
Shawn Willdenc38eae52016-02-22 23:28:34 +00001296 *
1297 * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001298 * biometric authentication only are <em>irreversibly invalidated</em> when a new
1299 * biometric is enrolled, or when all existing biometrics are deleted. That may be
Shawn Willdenc38eae52016-02-22 23:28:34 +00001300 * changed by calling this method with {@code invalidateKey} set to {@code false}.
1301 *
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001302 * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
Shawn Willdenc38eae52016-02-22 23:28:34 +00001303 * improves security by ensuring that an unauthorized person who obtains the password can't
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001304 * gain the use of biometric-authenticated keys by enrolling their own biometric. However,
Shawn Willdenc38eae52016-02-22 23:28:34 +00001305 * invalidating keys makes key-dependent operations impossible, requiring some fallback
1306 * procedure to authenticate the user and set up a new key.
1307 */
1308 @NonNull
1309 public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
1310 mInvalidatedByBiometricEnrollment = invalidateKey;
1311 return this;
1312 }
1313
1314 /**
Frank Salim21d9c1d2017-12-19 22:38:09 -08001315 * Sets whether this key should be protected by a StrongBox security chip.
1316 */
1317 @NonNull
1318 public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
1319 mIsStrongBoxBacked = isStrongBoxBacked;
1320 return this;
1321 }
1322
1323 /**
Brian C. Young9e874902018-03-26 11:40:13 -07001324 * Sets whether the keystore requires the screen to be unlocked before allowing decryption
Brian C. Young6f8fa9a2018-04-02 12:40:58 -07001325 * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
1326 * key while the screen is locked will fail. A locked device requires a PIN, password,
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001327 * biometric, or other trusted factor to access. While the screen is locked, the key can
Brian C. Young6f8fa9a2018-04-02 12:40:58 -07001328 * still be used for encryption or signature verification.
Brian Young36716eb2018-02-23 18:04:20 +00001329 */
1330 @NonNull
1331 public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
1332 mUnlockedDeviceRequired = unlockedDeviceRequired;
1333 return this;
1334 }
1335
1336 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001337 * Builds an instance of {@code KeyGenParameterSpec}.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001338 */
1339 @NonNull
1340 public KeyGenParameterSpec build() {
1341 return new KeyGenParameterSpec(
1342 mKeystoreAlias,
Alex Klyubin3876b1b2015-09-09 14:55:03 -07001343 mUid,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001344 mKeySize,
1345 mSpec,
1346 mCertificateSubject,
1347 mCertificateSerialNumber,
1348 mCertificateNotBefore,
1349 mCertificateNotAfter,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001350 mKeyValidityStart,
1351 mKeyValidityForOriginationEnd,
1352 mKeyValidityForConsumptionEnd,
1353 mPurposes,
1354 mDigests,
1355 mEncryptionPaddings,
1356 mSignaturePaddings,
1357 mBlockModes,
1358 mRandomizedEncryptionRequired,
1359 mUserAuthenticationRequired,
Shawn Willden8d8c7472016-02-02 08:27:39 -07001360 mUserAuthenticationValidityDurationSeconds,
Shawn Willden3c1830b2018-03-27 16:10:37 -06001361 mUserPresenceRequired,
Shawn Willden8d8c7472016-02-02 08:27:39 -07001362 mAttestationChallenge,
Shawn Willdenadef4962016-01-29 07:07:16 -07001363 mUniqueIdIncluded,
Shawn Willdenc38eae52016-02-22 23:28:34 +00001364 mUserAuthenticationValidWhileOnBody,
Frank Salim21d9c1d2017-12-19 22:38:09 -08001365 mInvalidatedByBiometricEnrollment,
David Zeuthena8e8b652017-10-25 14:25:55 -04001366 mIsStrongBoxBacked,
Brian Young36716eb2018-02-23 18:04:20 +00001367 mUserConfirmationRequired,
1368 mUnlockedDeviceRequired);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001369 }
1370 }
1371}