blob: 7ef7b1a7edcb989a513ded83e8ac1177e78984a6 [file] [log] [blame]
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001/*
2 * Copyright (C) 2015 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;
Brian C. Young1c5ee612018-04-10 08:43:53 -070022import android.annotation.TestApi;
Alex Klyubin83cc7a32015-06-16 10:44:11 -070023import android.app.KeyguardManager;
Kevin Chyn9374c9f2019-04-04 17:46:18 -070024import android.hardware.biometrics.BiometricManager;
25import android.hardware.biometrics.BiometricPrompt;
Rubin Xu59ced282017-01-30 23:39:12 +000026import android.security.GateKeeper;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070027
28import java.security.Key;
29import java.security.KeyStore.ProtectionParameter;
Kevin Chyn9374c9f2019-04-04 17:46:18 -070030import java.security.Signature;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070031import java.security.cert.Certificate;
32import java.util.Date;
33
34import javax.crypto.Cipher;
Alex Klyubin83cc7a32015-06-16 10:44:11 -070035import javax.crypto.Mac;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070036
37/**
38 * Specification of how a key or key pair is secured when imported into the
Alex Klyubin72245d72015-08-11 06:41:13 -070039 * <a href="{@docRoot}training/articles/keystore.html">Android Keystore system</a>. This class
40 * specifies authorized uses of the imported key, such as whether user authentication is required
41 * for using the key, what operations the key is authorized for (e.g., decryption, but not signing)
Trevor Johns682c24e2016-04-12 10:13:47 -070042 * with what parameters (e.g., only with a particular padding scheme or digest), and the key's
Alex Klyubin72245d72015-08-11 06:41:13 -070043 * validity start and end dates. Key use authorizations expressed in this class apply only to secret
44 * keys and private keys -- public keys can be used for any supported operations.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070045 *
Alex Klyubin72245d72015-08-11 06:41:13 -070046 * <p>To import a key or key pair into the Android Keystore, create an instance of this class using
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070047 * the {@link Builder} and pass the instance into {@link java.security.KeyStore#setEntry(String, java.security.KeyStore.Entry, ProtectionParameter) KeyStore.setEntry}
48 * with the key or key pair being imported.
49 *
Alex Klyubin72245d72015-08-11 06:41:13 -070050 * <p>To obtain the secret/symmetric or private key from the Android Keystore use
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070051 * {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)} or
52 * {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
Alex Klyubin72245d72015-08-11 06:41:13 -070053 * To obtain the public key from the Android Keystore use
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070054 * {@link java.security.KeyStore#getCertificate(String)} and then
55 * {@link Certificate#getPublicKey()}.
56 *
Alex Klyubin72245d72015-08-11 06:41:13 -070057 * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
58 * Keystore, its private keys implement {@link java.security.interfaces.ECKey} or
59 * {@link java.security.interfaces.RSAKey} interfaces whereas its public keys implement
60 * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
61 * interfaces.
62 *
63 * <p>NOTE: The key material of keys stored in the Android Keystore is not accessible.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070064 *
Alex Klyubincb3bb3f2015-06-16 12:31:34 -070065 * <p>Instances of this class are immutable.
66 *
Trevor Johns682c24e2016-04-12 10:13:47 -070067 * <p><h3>Known issues</h3>
68 * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be
69 * enforced even for public keys. To work around this issue extract the public key material to use
70 * outside of Android Keystore. For example:
71 * <pre> {@code
72 * PublicKey unrestrictedPublicKey =
73 * KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
74 * new X509EncodedKeySpec(publicKey.getEncoded()));
75 * }</pre>
76 *
Alex Klyubin72245d72015-08-11 06:41:13 -070077 * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
78 * This example illustrates how to import an AES key into the Android KeyStore under alias
Alex Klyubina5e21f0e2015-06-17 11:24:45 -070079 * {@code key1} authorized to be used only for encryption/decryption in GCM mode with no padding.
80 * The key must export its key material via {@link Key#getEncoded()} in {@code RAW} format.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070081 * <pre> {@code
82 * SecretKey key = ...; // AES key
83 *
84 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
85 * keyStore.load(null);
86 * keyStore.setEntry(
87 * "key1",
88 * new KeyStore.SecretKeyEntry(key),
89 * new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
Alex Klyubina5e21f0e2015-06-17 11:24:45 -070090 * .setBlockMode(KeyProperties.BLOCK_MODE_GCM)
91 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070092 * .build());
93 * // Key imported, obtain a reference to it.
94 * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
Alex Klyubin72245d72015-08-11 06:41:13 -070095 * // The original key can now be discarded.
96 *
97 * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
98 * cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
99 * ...
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700100 * }</pre>
101 *
Alex Klyubin72245d72015-08-11 06:41:13 -0700102 * <p><h3>Example: HMAC key for generating MACs using SHA-512</h3>
103 * This example illustrates how to import an HMAC key into the Android KeyStore under alias
104 * {@code key1} authorized to be used only for generating MACs using SHA-512 digest. The key must
105 * export its key material via {@link Key#getEncoded()} in {@code RAW} format.
106 * <pre> {@code
107 * SecretKey key = ...; // HMAC key of algorithm "HmacSHA512".
108 *
109 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
110 * keyStore.load(null);
111 * keyStore.setEntry(
112 * "key1",
113 * new KeyStore.SecretKeyEntry(key),
114 * new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());
115 * // Key imported, obtain a reference to it.
116 * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
117 * // The original key can now be discarded.
118 *
119 * Mac mac = Mac.getInstance("HmacSHA512");
120 * mac.init(keyStoreKey);
121 * ...
122 * }</pre>
123 *
124 * <p><h3>Example: EC key pair for signing/verification using ECDSA</h3>
125 * This example illustrates how to import an EC key pair into the Android KeyStore under alias
126 * {@code key2} with the private key authorized to be used only for signing with SHA-256 or SHA-512
Trevor Johns682c24e2016-04-12 10:13:47 -0700127 * digests. The use of the public key is unrestricted. Both the private and the public key must
128 * export their key material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format
129 * respectively.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700130 * <pre> {@code
131 * PrivateKey privateKey = ...; // EC private key
132 * Certificate[] certChain = ...; // Certificate chain with the first certificate
133 * // containing the corresponding EC public key.
134 *
135 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
136 * keyStore.load(null);
137 * keyStore.setEntry(
138 * "key2",
139 * new KeyStore.PrivateKeyEntry(privateKey, certChain),
140 * new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
Alex Klyubin72245d72015-08-11 06:41:13 -0700141 * .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
142 * .build());
143 * // Key pair imported, obtain a reference to it.
144 * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
145 * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
146 * // The original private key can now be discarded.
147 *
148 * Signature signature = Signature.getInstance("SHA256withECDSA");
149 * signature.initSign(keyStorePrivateKey);
150 * ...
151 * }</pre>
152 *
153 * <p><h3>Example: RSA key pair for signing/verification using PKCS#1 padding</h3>
154 * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
155 * {@code key2} with the private key authorized to be used only for signing using the PKCS#1
156 * signature padding scheme with SHA-256 digest and only if the user has been authenticated within
Trevor Johns682c24e2016-04-12 10:13:47 -0700157 * the last ten minutes. The use of the public key is unrestricted (see Known Issues). Both the
Alex Klyubin72245d72015-08-11 06:41:13 -0700158 * private and the public key must export their key material via {@link Key#getEncoded()} in
159 * {@code PKCS#8} and {@code X.509} format respectively.
160 * <pre> {@code
161 * PrivateKey privateKey = ...; // RSA private key
162 * Certificate[] certChain = ...; // Certificate chain with the first certificate
163 * // containing the corresponding RSA public key.
164 *
165 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
166 * keyStore.load(null);
167 * keyStore.setEntry(
168 * "key2",
169 * new KeyStore.PrivateKeyEntry(privateKey, certChain),
170 * new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700171 * .setDigests(KeyProperties.DIGEST_SHA256)
Alex Klyubin72245d72015-08-11 06:41:13 -0700172 * .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700173 * // Only permit this key to be used if the user
174 * // authenticated within the last ten minutes.
175 * .setUserAuthenticationRequired(true)
176 * .setUserAuthenticationValidityDurationSeconds(10 * 60)
177 * .build());
178 * // Key pair imported, obtain a reference to it.
179 * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
180 * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
Alex Klyubin72245d72015-08-11 06:41:13 -0700181 * // The original private key can now be discarded.
182 *
183 * Signature signature = Signature.getInstance("SHA256withRSA");
184 * signature.initSign(keyStorePrivateKey);
185 * ...
186 * }</pre>
187 *
188 * <p><h3>Example: RSA key pair for encryption/decryption using PKCS#1 padding</h3>
189 * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
190 * {@code key2} with the private key authorized to be used only for decryption using the PKCS#1
191 * encryption padding scheme. The use of public key is unrestricted, thus permitting encryption
192 * using any padding schemes and digests. Both the private and the public key must export their key
193 * material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format respectively.
194 * <pre> {@code
195 * PrivateKey privateKey = ...; // RSA private key
196 * Certificate[] certChain = ...; // Certificate chain with the first certificate
197 * // containing the corresponding RSA public key.
198 *
199 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
200 * keyStore.load(null);
201 * keyStore.setEntry(
202 * "key2",
203 * new KeyStore.PrivateKeyEntry(privateKey, certChain),
204 * new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
205 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
206 * .build());
207 * // Key pair imported, obtain a reference to it.
208 * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
209 * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
210 * // The original private key can now be discarded.
211 *
212 * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
213 * cipher.init(Cipher.DECRYPT_MODE, keyStorePrivateKey);
214 * ...
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700215 * }</pre>
216 */
Brian Young5437b812018-02-23 18:04:20 +0000217public final class KeyProtection implements ProtectionParameter, UserAuthArgs {
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700218 private final Date mKeyValidityStart;
219 private final Date mKeyValidityForOriginationEnd;
220 private final Date mKeyValidityForConsumptionEnd;
221 private final @KeyProperties.PurposeEnum int mPurposes;
222 private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
223 private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
224 private final @KeyProperties.DigestEnum String[] mDigests;
225 private final @KeyProperties.BlockModeEnum String[] mBlockModes;
226 private final boolean mRandomizedEncryptionRequired;
227 private final boolean mUserAuthenticationRequired;
Max Bires04b682d2020-01-14 16:10:36 -0800228 private final @KeyProperties.AuthEnum int mUserAuthenticationType;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700229 private final int mUserAuthenticationValidityDurationSeconds;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600230 private final boolean mUserPresenceRequred;
Shawn Willdenadef4962016-01-29 07:07:16 -0700231 private final boolean mUserAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000232 private final boolean mInvalidatedByBiometricEnrollment;
Rubin Xu59ced282017-01-30 23:39:12 +0000233 private final long mBoundToSecureUserId;
Rubin Xu12b644d2017-04-21 19:21:42 +0100234 private final boolean mCriticalToDeviceEncryption;
David Zeuthena8e8b652017-10-25 14:25:55 -0400235 private final boolean mUserConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000236 private final boolean mUnlockedDeviceRequired;
Frank Salim4b9fee52018-04-12 03:09:44 -0700237 private final boolean mIsStrongBoxBacked;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700238
239 private KeyProtection(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700240 Date keyValidityStart,
241 Date keyValidityForOriginationEnd,
242 Date keyValidityForConsumptionEnd,
243 @KeyProperties.PurposeEnum int purposes,
244 @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
245 @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
246 @KeyProperties.DigestEnum String[] digests,
247 @KeyProperties.BlockModeEnum String[] blockModes,
248 boolean randomizedEncryptionRequired,
249 boolean userAuthenticationRequired,
Max Bires04b682d2020-01-14 16:10:36 -0800250 @KeyProperties.AuthEnum int userAuthenticationType,
Shawn Willdenadef4962016-01-29 07:07:16 -0700251 int userAuthenticationValidityDurationSeconds,
Shawn Willden3c1830b2018-03-27 16:10:37 -0600252 boolean userPresenceRequred,
Shawn Willdenc38eae52016-02-22 23:28:34 +0000253 boolean userAuthenticationValidWhileOnBody,
Rubin Xu59ced282017-01-30 23:39:12 +0000254 boolean invalidatedByBiometricEnrollment,
Rubin Xu12b644d2017-04-21 19:21:42 +0100255 long boundToSecureUserId,
David Zeuthena8e8b652017-10-25 14:25:55 -0400256 boolean criticalToDeviceEncryption,
Brian Young36716eb2018-02-23 18:04:20 +0000257 boolean userConfirmationRequired,
Frank Salim4b9fee52018-04-12 03:09:44 -0700258 boolean unlockedDeviceRequired,
259 boolean isStrongBoxBacked) {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700260 mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
261 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
262 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700263 mPurposes = purposes;
264 mEncryptionPaddings =
265 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
266 mSignaturePaddings =
267 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
268 mDigests = ArrayUtils.cloneIfNotEmpty(digests);
269 mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
270 mRandomizedEncryptionRequired = randomizedEncryptionRequired;
271 mUserAuthenticationRequired = userAuthenticationRequired;
Max Bires04b682d2020-01-14 16:10:36 -0800272 mUserAuthenticationType = userAuthenticationType;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700273 mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600274 mUserPresenceRequred = userPresenceRequred;
Shawn Willdenadef4962016-01-29 07:07:16 -0700275 mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000276 mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
Rubin Xu59ced282017-01-30 23:39:12 +0000277 mBoundToSecureUserId = boundToSecureUserId;
Rubin Xu12b644d2017-04-21 19:21:42 +0100278 mCriticalToDeviceEncryption = criticalToDeviceEncryption;
David Zeuthena8e8b652017-10-25 14:25:55 -0400279 mUserConfirmationRequired = userConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000280 mUnlockedDeviceRequired = unlockedDeviceRequired;
Frank Salim4b9fee52018-04-12 03:09:44 -0700281 mIsStrongBoxBacked = isStrongBoxBacked;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700282 }
283
284 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700285 * Gets the time instant before which the key is not yet valid.
286 *
287 * @return instant or {@code null} if not restricted.
288 */
289 @Nullable
290 public Date getKeyValidityStart() {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700291 return Utils.cloneIfNotNull(mKeyValidityStart);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700292 }
293
294 /**
295 * Gets the time instant after which the key is no long valid for decryption and verification.
296 *
297 * @return instant or {@code null} if not restricted.
298 */
299 @Nullable
300 public Date getKeyValidityForConsumptionEnd() {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700301 return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700302 }
303
304 /**
305 * Gets the time instant after which the key is no long valid for encryption and signing.
306 *
307 * @return instant or {@code null} if not restricted.
308 */
309 @Nullable
310 public Date getKeyValidityForOriginationEnd() {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700311 return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700312 }
313
314 /**
315 * Gets the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
316 * Attempts to use the key for any other purpose will be rejected.
317 *
318 * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
319 */
320 public @KeyProperties.PurposeEnum int getPurposes() {
321 return mPurposes;
322 }
323
324 /**
325 * Gets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code PKCS1Padding},
326 * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to use
327 * the key with any other padding scheme will be rejected.
328 *
329 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
330 */
331 @NonNull
332 public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
333 return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
334 }
335
336 /**
337 * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
338 * can be used when signing/verifying. Attempts to use the key with any other padding scheme
339 * will be rejected.
340 *
341 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
342 */
343 @NonNull
344 public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
345 return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
346 }
347
348 /**
349 * Gets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the key
350 * can be used.
351 *
352 * <p>See {@link KeyProperties}.{@code DIGEST} constants.
353 *
354 * @throws IllegalStateException if this set has not been specified.
355 *
356 * @see #isDigestsSpecified()
357 */
358 @NonNull
359 public @KeyProperties.DigestEnum String[] getDigests() {
360 if (mDigests == null) {
361 throw new IllegalStateException("Digests not specified");
362 }
363 return ArrayUtils.cloneIfNotEmpty(mDigests);
364 }
365
366 /**
367 * Returns {@code true} if the set of digest algorithms with which the key can be used has been
368 * specified.
369 *
370 * @see #getDigests()
371 */
372 public boolean isDigestsSpecified() {
373 return mDigests != null;
374 }
375
376 /**
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700377 * 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 -0700378 * when encrypting/decrypting. Attempts to use the key with any other block modes will be
379 * rejected.
380 *
381 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
382 */
383 @NonNull
384 public @KeyProperties.BlockModeEnum String[] getBlockModes() {
385 return ArrayUtils.cloneIfNotEmpty(mBlockModes);
386 }
387
388 /**
389 * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
390 * different ciphertexts for the same plaintext every time. The formal cryptographic property
391 * being required is <em>indistinguishability under chosen-plaintext attack ({@code
392 * IND-CPA})</em>. This property is important because it mitigates several classes of
393 * weaknesses due to which ciphertext may leak information about plaintext. For example, if a
394 * given plaintext always produces the same ciphertext, an attacker may see the repeated
395 * ciphertexts and be able to deduce something about the plaintext.
396 */
397 public boolean isRandomizedEncryptionRequired() {
398 return mRandomizedEncryptionRequired;
399 }
400
401 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700402 * Returns {@code true} if the key is authorized to be used only if the user has been
403 * authenticated.
404 *
405 * <p>This authorization applies only to secret key and private key operations. Public key
406 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700407 *
408 * @see #getUserAuthenticationValidityDurationSeconds()
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700409 * @see Builder#setUserAuthenticationRequired(boolean)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700410 */
411 public boolean isUserAuthenticationRequired() {
412 return mUserAuthenticationRequired;
413 }
414
415 /**
David Zeuthena8e8b652017-10-25 14:25:55 -0400416 * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
417 * user.
418 *
419 * Confirmation is separate from user authentication (see
420 * {@link #isUserAuthenticationRequired()}). Keys can be created that require confirmation but
421 * not user authentication, or user authentication but not confirmation, or both. Confirmation
422 * verifies that some user with physical possession of the device has approved a displayed
423 * message. User authentication verifies that the correct user is present and has
424 * authenticated.
425 *
426 * <p>This authorization applies only to secret key and private key operations. Public key
427 * operations are not restricted.
428 *
429 * @see Builder#setUserConfirmationRequired(boolean)
430 */
431 public boolean isUserConfirmationRequired() {
432 return mUserConfirmationRequired;
433 }
434
Max Bires04b682d2020-01-14 16:10:36 -0800435 public @KeyProperties.AuthEnum int getUserAuthenticationType() {
436 return mUserAuthenticationType;
437 }
438
David Zeuthena8e8b652017-10-25 14:25:55 -0400439 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700440 * Gets the duration of time (seconds) for which this key is authorized to be used after the
441 * user is successfully authenticated. This has effect only if user authentication is required
442 * (see {@link #isUserAuthenticationRequired()}).
443 *
444 * <p>This authorization applies only to secret key and private key operations. Public key
445 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700446 *
447 * @return duration in seconds or {@code -1} if authentication is required for every use of the
448 * key.
449 *
450 * @see #isUserAuthenticationRequired()
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700451 * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700452 */
453 public int getUserAuthenticationValidityDurationSeconds() {
454 return mUserAuthenticationValidityDurationSeconds;
455 }
456
457 /**
Brian Young5437b812018-02-23 18:04:20 +0000458 * Returns {@code true} if the key is authorized to be used only if a test of user presence has
459 * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls.
Allen Webbbe108912018-03-29 09:50:45 -0700460 * It requires that the KeyStore implementation have a direct way to validate the user presence
461 * for example a KeyStore hardware backed strongbox can use a button press that is observable
Allen Webb9b5853d2018-04-10 10:33:42 -0700462 * in hardware. A test for user presence is tangential to authentication. The test can be part
463 * of an authentication step as long as this step can be validated by the hardware protecting
464 * the key and cannot be spoofed. For example, a physical button press can be used as a test of
465 * user presence if the other pins connected to the button are not able to simulate a button
466 * press. There must be no way for the primary processor to fake a button press, or that
467 * button must not be used as a test of user presence.
Brian Young5437b812018-02-23 18:04:20 +0000468 */
Shawn Willden3c1830b2018-03-27 16:10:37 -0600469 public boolean isUserPresenceRequired() {
470 return mUserPresenceRequred;
Brian Young5437b812018-02-23 18:04:20 +0000471 }
472
473 /**
Shawn Willden26e8d552016-06-14 17:27:10 -0600474 * Returns {@code true} if the key will be de-authorized when the device is removed from the
475 * user's body. This option has no effect on keys that don't have an authentication validity
476 * duration, and has no effect if the device lacks an on-body sensor.
Shawn Willdenadef4962016-01-29 07:07:16 -0700477 *
478 * <p>Authorization applies only to secret key and private key operations. Public key operations
479 * are not restricted.
480 *
481 * @see #isUserAuthenticationRequired()
482 * @see #getUserAuthenticationValidityDurationSeconds()
483 * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
484 */
485 public boolean isUserAuthenticationValidWhileOnBody() {
486 return mUserAuthenticationValidWhileOnBody;
487 }
488
489 /**
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700490 * Returns {@code true} if the key is irreversibly invalidated when a new biometric is
491 * enrolled or all enrolled biometrics are removed. This has effect only for keys that
492 * require biometric user authentication for every use.
Shawn Willdenc38eae52016-02-22 23:28:34 +0000493 *
494 * @see #isUserAuthenticationRequired()
495 * @see #getUserAuthenticationValidityDurationSeconds()
496 * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
497 */
498 public boolean isInvalidatedByBiometricEnrollment() {
499 return mInvalidatedByBiometricEnrollment;
500 }
501
502 /**
Rubin Xu59ced282017-01-30 23:39:12 +0000503 * Return the secure user id that this key should be bound to.
504 *
505 * Normally an authentication-bound key is tied to the secure user id of the current user
506 * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the authenticator
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700507 * id of the current biometric set for keys requiring explicit biometric authorization).
Rubin Xu59ced282017-01-30 23:39:12 +0000508 * If this parameter is set (this method returning non-zero value), the key should be tied to
509 * the specified secure user id, overriding the logic above.
510 *
511 * This is only applicable when {@link #isUserAuthenticationRequired} is {@code true}
512 *
513 * @see KeymasterUtils#addUserAuthArgs
514 * @hide
515 */
Brian C. Young1c5ee612018-04-10 08:43:53 -0700516 @TestApi
Rubin Xu59ced282017-01-30 23:39:12 +0000517 public long getBoundToSpecificSecureUserId() {
518 return mBoundToSecureUserId;
519 }
520
521 /**
Rubin Xu12b644d2017-04-21 19:21:42 +0100522 * Return whether this key is critical to the device encryption flow.
523 *
524 * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
525 * @hide
526 */
527 public boolean isCriticalToDeviceEncryption() {
528 return mCriticalToDeviceEncryption;
529 }
530
531 /**
Brian C. Young1c5ee612018-04-10 08:43:53 -0700532 * Returns {@code true} if the screen must be unlocked for this key to be used for decryption or
533 * signing. Encryption and signature verification will still be available when the screen is
Brian C. Young6f8fa9a2018-04-02 12:40:58 -0700534 * locked.
Brian Young36716eb2018-02-23 18:04:20 +0000535 *
536 * @see Builder#setUnlockedDeviceRequired(boolean)
537 */
538 public boolean isUnlockedDeviceRequired() {
539 return mUnlockedDeviceRequired;
540 }
541
542 /**
Frank Salim4b9fee52018-04-12 03:09:44 -0700543 * Returns {@code true} if the key is protected by a Strongbox security chip.
544 * @hide
545 */
546 public boolean isStrongBoxBacked() {
547 return mIsStrongBoxBacked;
548 }
549
550 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700551 * Builder of {@link KeyProtection} instances.
552 */
553 public final static class Builder {
554 private @KeyProperties.PurposeEnum int mPurposes;
555
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700556 private Date mKeyValidityStart;
557 private Date mKeyValidityForOriginationEnd;
558 private Date mKeyValidityForConsumptionEnd;
559 private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
560 private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
561 private @KeyProperties.DigestEnum String[] mDigests;
562 private @KeyProperties.BlockModeEnum String[] mBlockModes;
563 private boolean mRandomizedEncryptionRequired = true;
564 private boolean mUserAuthenticationRequired;
Max Birese5b66862020-03-03 21:05:02 -0800565 private @KeyProperties.AuthEnum int mUserAuthenticationType =
566 KeyProperties.AUTH_BIOMETRIC_STRONG;
567 private int mUserAuthenticationValidityDurationSeconds = 0;
Shawn Willden3c1830b2018-03-27 16:10:37 -0600568 private boolean mUserPresenceRequired = false;
Shawn Willdenadef4962016-01-29 07:07:16 -0700569 private boolean mUserAuthenticationValidWhileOnBody;
Shawn Willdenc38eae52016-02-22 23:28:34 +0000570 private boolean mInvalidatedByBiometricEnrollment = true;
David Zeuthena8e8b652017-10-25 14:25:55 -0400571 private boolean mUserConfirmationRequired;
Brian Young36716eb2018-02-23 18:04:20 +0000572 private boolean mUnlockedDeviceRequired = false;
573
Rubin Xu59ced282017-01-30 23:39:12 +0000574 private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID;
Rubin Xu12b644d2017-04-21 19:21:42 +0100575 private boolean mCriticalToDeviceEncryption = false;
Frank Salim4b9fee52018-04-12 03:09:44 -0700576 private boolean mIsStrongBoxBacked = false;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800577
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700578 /**
579 * Creates a new instance of the {@code Builder}.
580 *
581 * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
582 * used. Attempts to use the key for any other purpose will be rejected.
583 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700584 * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
585 */
586 public Builder(@KeyProperties.PurposeEnum int purposes) {
587 mPurposes = purposes;
588 }
589
590 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700591 * Sets the time instant before which the key is not yet valid.
592 *
593 * <p>By default, the key is valid at any instant.
594 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700595 * @see #setKeyValidityEnd(Date)
596 */
597 @NonNull
598 public Builder setKeyValidityStart(Date startDate) {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700599 mKeyValidityStart = Utils.cloneIfNotNull(startDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700600 return this;
601 }
602
603 /**
604 * Sets the time instant after which the key is no longer valid.
605 *
606 * <p>By default, the key is valid at any instant.
607 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700608 * @see #setKeyValidityStart(Date)
609 * @see #setKeyValidityForConsumptionEnd(Date)
610 * @see #setKeyValidityForOriginationEnd(Date)
611 */
612 @NonNull
613 public Builder setKeyValidityEnd(Date endDate) {
614 setKeyValidityForOriginationEnd(endDate);
615 setKeyValidityForConsumptionEnd(endDate);
616 return this;
617 }
618
619 /**
620 * Sets the time instant after which the key is no longer valid for encryption and signing.
621 *
622 * <p>By default, the key is valid at any instant.
623 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700624 * @see #setKeyValidityForConsumptionEnd(Date)
625 */
626 @NonNull
627 public Builder setKeyValidityForOriginationEnd(Date endDate) {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700628 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700629 return this;
630 }
631
632 /**
633 * Sets the time instant after which the key is no longer valid for decryption and
634 * verification.
635 *
636 * <p>By default, the key is valid at any instant.
637 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700638 * @see #setKeyValidityForOriginationEnd(Date)
639 */
640 @NonNull
641 public Builder setKeyValidityForConsumptionEnd(Date endDate) {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700642 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700643 return this;
644 }
645
646 /**
647 * Sets the set of padding schemes (e.g., {@code OAEPPadding}, {@code PKCS7Padding},
648 * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to
649 * use the key with any other padding scheme will be rejected.
650 *
651 * <p>This must be specified for keys which are used for encryption/decryption.
652 *
Alex Klyubindcf3d352015-06-11 14:44:46 -0700653 * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
654 * is usually necessary to authorize the use of no/any padding
Alex Klyubine4928a22015-07-21 13:38:48 -0700655 * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
656 * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
Alex Klyubindcf3d352015-06-11 14:44:46 -0700657 * required by some cipher suites, and some stacks request decryption using no padding
658 * whereas others request PKCS#1 padding.
659 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700660 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
661 */
662 @NonNull
663 public Builder setEncryptionPaddings(
664 @KeyProperties.EncryptionPaddingEnum String... paddings) {
665 mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
666 return this;
667 }
668
669 /**
670 * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
671 * can be used when signing/verifying. Attempts to use the key with any other padding scheme
672 * will be rejected.
673 *
674 * <p>This must be specified for RSA keys which are used for signing/verification.
675 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700676 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
677 */
678 @NonNull
679 public Builder setSignaturePaddings(
680 @KeyProperties.SignaturePaddingEnum String... paddings) {
681 mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
682 return this;
683 }
684
685 /**
686 * Sets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the
Alex Klyubin38677092015-06-22 13:42:46 -0700687 * key can be used. Attempts to use the key with any other digest algorithm will be
688 * rejected.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700689 *
Alex Klyubin38677092015-06-22 13:42:46 -0700690 * <p>This must be specified for signing/verification keys and RSA encryption/decryption
691 * keys used with RSA OAEP padding scheme because these operations involve a digest. For
692 * HMAC keys, the default is the digest specified in {@link Key#getAlgorithm()} (e.g.,
Alex Klyubinc58153b2015-07-08 09:31:23 -0700693 * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
694 * for more than one digest.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700695 *
Alex Klyubindcf3d352015-06-11 14:44:46 -0700696 * <p>For private keys used for TLS/SSL client or server authentication it is usually
697 * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
698 * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
699 * a private key to sign it.
700 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700701 * <p>See {@link KeyProperties}.{@code DIGEST} constants.
702 */
703 @NonNull
704 public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
705 mDigests = ArrayUtils.cloneIfNotEmpty(digests);
706 return this;
707 }
708
709 /**
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700710 * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
711 * used when encrypting/decrypting. Attempts to use the key with any other block modes will
712 * be rejected.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700713 *
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700714 * <p>This must be specified for symmetric encryption/decryption keys.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700715 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700716 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
717 */
718 @NonNull
719 public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
720 mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
721 return this;
722 }
723
724 /**
725 * Sets whether encryption using this key must be sufficiently randomized to produce
726 * different ciphertexts for the same plaintext every time. The formal cryptographic
727 * property being required is <em>indistinguishability under chosen-plaintext attack
728 * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
729 * of weaknesses due to which ciphertext may leak information about plaintext. For example,
730 * if a given plaintext always produces the same ciphertext, an attacker may see the
731 * repeated ciphertexts and be able to deduce something about the plaintext.
732 *
733 * <p>By default, {@code IND-CPA} is required.
734 *
735 * <p>When {@code IND-CPA} is required:
736 * <ul>
737 * <li>transformation which do not offer {@code IND-CPA}, such as symmetric ciphers using
738 * {@code ECB} mode or RSA encryption without padding, are prohibited;</li>
Alex Klyubina5e21f0e2015-06-17 11:24:45 -0700739 * <li>in transformations which use an IV, such as symmetric ciphers in {@code GCM},
740 * {@code CBC}, and {@code CTR} block modes, caller-provided IVs are rejected when
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700741 * encrypting, to ensure that only random IVs are used.</li>
742 *
743 * <p>Before disabling this requirement, consider the following approaches instead:
744 * <ul>
745 * <li>If you are generating a random IV for encryption and then initializing a {@code}
746 * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
747 * instead. This will occur if the {@code Cipher} is initialized for encryption without an
748 * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
749 * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
750 * random, such as the name of the file being encrypted, or transaction ID, or password,
751 * or a device identifier), consider changing your design to use a random IV which will then
752 * be provided in addition to the ciphertext to the entities which need to decrypt the
753 * ciphertext.</li>
754 * <li>If you are using RSA encryption without padding, consider switching to padding
755 * schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
756 * </ul>
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700757 */
758 @NonNull
759 public Builder setRandomizedEncryptionRequired(boolean required) {
760 mRandomizedEncryptionRequired = required;
761 return this;
762 }
763
764 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700765 * Sets whether this key is authorized to be used only if the user has been authenticated.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700766 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700767 * <p>By default, the key is authorized to be used regardless of whether the user has been
768 * authenticated.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700769 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700770 * <p>When user authentication is required:
771 * <ul>
772 * <li>The key can only be import if secure lock screen is set up (see
773 * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
774 * authentication takes place for every use of the key (see
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700775 * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
776 * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700777 * <li>The use of the key must be authorized by the user by authenticating to this Android
778 * device using a subset of their secure lock screen credentials such as
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700779 * password/PIN/pattern or biometric.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700780 * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
781 * information</a>.
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700782 * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
783 * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
784 * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
785 * Additionally, if the key requires that user authentication takes place for every use of
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700786 * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
787 * no more biometrics are enrolled, unless {@link
Shawn Willdenc38eae52016-02-22 23:28:34 +0000788 * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
789 * enrollment. Attempts to initialize cryptographic operations using such keys will throw
790 * {@link KeyPermanentlyInvalidatedException}.</li> </ul>
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700791 *
792 * <p>This authorization applies only to secret key and private key operations. Public key
793 * operations are not restricted.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700794 *
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700795 * @see #setUserAuthenticationValidityDurationSeconds(int)
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700796 * @see KeyguardManager#isDeviceSecure()
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700797 * @see BiometricManager#canAuthenticate()
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700798 */
799 @NonNull
800 public Builder setUserAuthenticationRequired(boolean required) {
801 mUserAuthenticationRequired = required;
802 return this;
803 }
804
805 /**
David Zeuthena8e8b652017-10-25 14:25:55 -0400806 * Sets whether this key is authorized to be used only for messages confirmed by the
807 * user.
808 *
809 * Confirmation is separate from user authentication (see
810 * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require
811 * confirmation but not user authentication, or user authentication but not confirmation,
812 * or both. Confirmation verifies that some user with physical possession of the device has
813 * approved a displayed message. User authentication verifies that the correct user is
814 * present and has authenticated.
815 *
816 * <p>This authorization applies only to secret key and private key operations. Public key
817 * operations are not restricted.
818 *
Aurimas Liutikase701dc12018-06-01 16:04:37 -0700819 * See {@link android.security.ConfirmationPrompt} class for
David Zeuthena8e8b652017-10-25 14:25:55 -0400820 * more details about user confirmations.
821 */
822 @NonNull
823 public Builder setUserConfirmationRequired(boolean required) {
824 mUserConfirmationRequired = required;
825 return this;
826 }
827
828 /**
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700829 * Sets the duration of time (seconds) for which this key is authorized to be used after the
830 * user is successfully authenticated. This has effect if the key requires user
831 * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700832 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700833 * <p>By default, if user authentication is required, it must take place for every use of
834 * the key.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700835 *
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700836 * <p>Cryptographic operations involving keys which require user authentication to take
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700837 * place for every operation can only use biometric authentication. This is achieved by
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700838 * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700839 * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
840 * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700841 * the cryptographic operation only if the authentication flow succeeds.
842 *
843 * <p>Cryptographic operations involving keys which are authorized to be used for a duration
844 * of time after a successful user authentication event can only use secure lock screen
845 * authentication. These cryptographic operations will throw
846 * {@link UserNotAuthenticatedException} during initialization if the user needs to be
847 * authenticated to proceed. This situation can be resolved by the user unlocking the secure
848 * lock screen of the Android or by going through the confirm credential flow initiated by
849 * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
850 * Once resolved, initializing a new cryptographic operation using this key (or any other
851 * key which is authorized to be used for a fixed duration of time after user
852 * authentication) should succeed provided the user authentication flow completed
853 * successfully.
854 *
855 * @param seconds duration in seconds or {@code -1} if user authentication must take place
856 * for every use of the key.
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700857 *
858 * @see #setUserAuthenticationRequired(boolean)
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700859 * @see BiometricPrompt
860 * @see BiometricPrompt.CryptoObject
Alex Klyubin83cc7a32015-06-16 10:44:11 -0700861 * @see KeyguardManager
Max Bires04b682d2020-01-14 16:10:36 -0800862 * @deprecated See {@link #setUserAuthenticationParameters(int, int)}
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700863 */
Max Bires04b682d2020-01-14 16:10:36 -0800864 @Deprecated
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700865 @NonNull
866 public Builder setUserAuthenticationValidityDurationSeconds(
867 @IntRange(from = -1) int seconds) {
Alex Klyubincb3bb3f2015-06-16 12:31:34 -0700868 if (seconds < -1) {
869 throw new IllegalArgumentException("seconds must be -1 or larger");
870 }
Max Bires04b682d2020-01-14 16:10:36 -0800871 if (seconds == -1) {
872 return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
873 }
874 return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_BIOMETRIC_STRONG);
875 }
876
877 /**
878 * Sets the duration of time (seconds) and authorization type for which this key is
879 * authorized to be used after the user is successfully authenticated. This has effect if
880 * the key requires user authentication for its use (see
881 * {@link #setUserAuthenticationRequired(boolean)}).
882 *
883 * <p>By default, if user authentication is required, it must take place for every use of
884 * the key.
885 *
886 * <p>These cryptographic operations will throw {@link UserNotAuthenticatedException} during
887 * initialization if the user needs to be authenticated to proceed. This situation can be
888 * resolved by the user authenticating with the appropriate biometric or credential as
889 * required by the key. See {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)}
890 * and {@link BiometricManager.Authenticators}.
891 *
892 * <p>Once resolved, initializing a new cryptographic operation using this key (or any other
893 * key which is authorized to be used for a fixed duration of time after user
894 * authentication) should succeed provided the user authentication flow completed
895 * successfully.
896 *
897 * @param timeout duration in seconds or {@code 0} if user authentication must take place
898 * for every use of the key. {@code -1} is also accepted for legacy purposes. It is
899 * functionally the same as {@code 0}.
900 * @param type set of authentication types which can authorize use of the key. See
901 * {@link KeyProperties}.{@code AUTH} flags.
902 *
903 * @see #setUserAuthenticationRequired(boolean)
904 * @see BiometricPrompt
905 * @see BiometricPrompt.CryptoObject
906 * @see KeyguardManager
907 */
908 @NonNull
909 public Builder setUserAuthenticationParameters(@IntRange(from = -1) int timeout,
910 @KeyProperties.AuthEnum int type) {
911 if (timeout < -1) {
912 throw new IllegalArgumentException("timeout must be -1 or larger");
913 } else if (timeout == -1) {
914 timeout = 0;
915 }
916 mUserAuthenticationValidityDurationSeconds = timeout;
917 mUserAuthenticationType = type;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700918 return this;
919 }
920
921 /**
Brian Young5437b812018-02-23 18:04:20 +0000922 * Sets whether a test of user presence is required to be performed between the
Allen Webb9b5853d2018-04-10 10:33:42 -0700923 * {@code Signature.initSign()} and {@code Signature.sign()} method calls. It requires that
924 * the KeyStore implementation have a direct way to validate the user presence for example
925 * a KeyStore hardware backed strongbox can use a button press that is observable in
926 * hardware. A test for user presence is tangential to authentication. The test can be part
927 * of an authentication step as long as this step can be validated by the hardware
928 * protecting the key and cannot be spoofed. For example, a physical button press can be
929 * used as a test of user presence if the other pins connected to the button are not able
930 * to simulate a button press. There must be no way for the primary processor to fake a
931 * button press, or that button must not be used as a test of user presence.
Brian Young5437b812018-02-23 18:04:20 +0000932 */
933 @NonNull
Shawn Willden3c1830b2018-03-27 16:10:37 -0600934 public Builder setUserPresenceRequired(boolean required) {
935 mUserPresenceRequired = required;
Brian Young5437b812018-02-23 18:04:20 +0000936 return this;
937 }
938
939 /**
Shawn Willden26e8d552016-06-14 17:27:10 -0600940 * Sets whether the key will remain authorized only until the device is removed from the
941 * user's body up to the limit of the authentication validity period (see
942 * {@link #setUserAuthenticationValidityDurationSeconds} and
943 * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
944 * user's body, the key will be considered unauthorized and the user will need to
945 * re-authenticate to use it. For keys without an authentication validity period this
946 * parameter has no effect.
Shawn Willdenadef4962016-01-29 07:07:16 -0700947 *
Shawn Willden26e8d552016-06-14 17:27:10 -0600948 * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
949 * effect; the device will always be considered to be "on-body" and the key will therefore
950 * remain authorized until the validity period ends.
Shawn Willdenadef4962016-01-29 07:07:16 -0700951 *
Shawn Willden26e8d552016-06-14 17:27:10 -0600952 * @param remainsValid if {@code true}, and if the device supports on-body detection, key
953 * will be invalidated when the device is removed from the user's body or when the
954 * authentication validity expires, whichever occurs first.
Shawn Willdenadef4962016-01-29 07:07:16 -0700955 */
956 @NonNull
957 public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
958 mUserAuthenticationValidWhileOnBody = remainsValid;
959 return this;
960 }
961
962 /**
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700963 * Sets whether this key should be invalidated on biometric enrollment. This
Shawn Willdenc38eae52016-02-22 23:28:34 +0000964 * applies only to keys which require user authentication (see {@link
965 * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
966 * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700967 * valid for biometric authentication only.
Shawn Willdenc38eae52016-02-22 23:28:34 +0000968 *
969 * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700970 * biometric authentication only are <em>irreversibly invalidated</em> when a new
971 * biometric is enrolled, or when all existing biometrics are deleted. That may be
Shawn Willdenc38eae52016-02-22 23:28:34 +0000972 * changed by calling this method with {@code invalidateKey} set to {@code false}.
973 *
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700974 * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
Shawn Willdenc38eae52016-02-22 23:28:34 +0000975 * improves security by ensuring that an unauthorized person who obtains the password can't
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700976 * gain the use of biometric-authenticated keys by enrolling their own biometric. However,
Shawn Willdenc38eae52016-02-22 23:28:34 +0000977 * invalidating keys makes key-dependent operations impossible, requiring some fallback
978 * procedure to authenticate the user and set up a new key.
979 */
980 @NonNull
981 public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
982 mInvalidatedByBiometricEnrollment = invalidateKey;
983 return this;
984 }
985
986 /**
Rubin Xu59ced282017-01-30 23:39:12 +0000987 * Set the secure user id that this key should be bound to.
988 *
989 * Normally an authentication-bound key is tied to the secure user id of the current user
990 * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the
Kevin Chyn9374c9f2019-04-04 17:46:18 -0700991 * authenticator id of the current biometric set for keys requiring explicit biometric
Rubin Xu59ced282017-01-30 23:39:12 +0000992 * authorization). If this parameter is set (this method returning non-zero value), the key
993 * should be tied to the specified secure user id, overriding the logic above.
994 *
995 * This is only applicable when {@link #setUserAuthenticationRequired} is set to
996 * {@code true}
997 *
998 * @see KeyProtection#getBoundToSpecificSecureUserId()
999 * @hide
1000 */
Brian C. Young1c5ee612018-04-10 08:43:53 -07001001 @TestApi
Rubin Xu59ced282017-01-30 23:39:12 +00001002 public Builder setBoundToSpecificSecureUserId(long secureUserId) {
1003 mBoundToSecureUserId = secureUserId;
1004 return this;
1005 }
1006
1007 /**
Rubin Xu12b644d2017-04-21 19:21:42 +01001008 * Set whether this key is critical to the device encryption flow
1009 *
1010 * This is a special flag only available to system servers to indicate the current key
1011 * is part of the device encryption flow.
1012 *
1013 * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
1014 * @hide
1015 */
1016 public Builder setCriticalToDeviceEncryption(boolean critical) {
1017 mCriticalToDeviceEncryption = critical;
1018 return this;
1019 }
1020
1021 /**
Brian C. Young9e874902018-03-26 11:40:13 -07001022 * Sets whether the keystore requires the screen to be unlocked before allowing decryption
Brian C. Young6f8fa9a2018-04-02 12:40:58 -07001023 * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
1024 * key while the screen is locked will fail. A locked device requires a PIN, password,
Kevin Chyn9374c9f2019-04-04 17:46:18 -07001025 * biometric, or other trusted factor to access. While the screen is locked, the key can
Brian C. Young6f8fa9a2018-04-02 12:40:58 -07001026 * still be used for encryption or signature verification.
Brian Young36716eb2018-02-23 18:04:20 +00001027 */
1028 @NonNull
1029 public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
1030 mUnlockedDeviceRequired = unlockedDeviceRequired;
1031 return this;
1032 }
1033
1034 /**
Frank Salim4b9fee52018-04-12 03:09:44 -07001035 * Sets whether this key should be protected by a StrongBox security chip.
1036 * @hide
1037 */
1038 @NonNull
1039 public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
1040 mIsStrongBoxBacked = isStrongBoxBacked;
1041 return this;
1042 }
1043
1044 /**
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001045 * Builds an instance of {@link KeyProtection}.
1046 *
1047 * @throws IllegalArgumentException if a required field is missing
1048 */
1049 @NonNull
1050 public KeyProtection build() {
1051 return new KeyProtection(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001052 mKeyValidityStart,
1053 mKeyValidityForOriginationEnd,
1054 mKeyValidityForConsumptionEnd,
1055 mPurposes,
1056 mEncryptionPaddings,
1057 mSignaturePaddings,
1058 mDigests,
1059 mBlockModes,
1060 mRandomizedEncryptionRequired,
1061 mUserAuthenticationRequired,
Max Bires04b682d2020-01-14 16:10:36 -08001062 mUserAuthenticationType,
Shawn Willdenadef4962016-01-29 07:07:16 -07001063 mUserAuthenticationValidityDurationSeconds,
Shawn Willden3c1830b2018-03-27 16:10:37 -06001064 mUserPresenceRequired,
Shawn Willdenc38eae52016-02-22 23:28:34 +00001065 mUserAuthenticationValidWhileOnBody,
Rubin Xu59ced282017-01-30 23:39:12 +00001066 mInvalidatedByBiometricEnrollment,
Rubin Xu12b644d2017-04-21 19:21:42 +01001067 mBoundToSecureUserId,
David Zeuthena8e8b652017-10-25 14:25:55 -04001068 mCriticalToDeviceEncryption,
Brian Young36716eb2018-02-23 18:04:20 +00001069 mUserConfirmationRequired,
Frank Salim4b9fee52018-04-12 03:09:44 -07001070 mUnlockedDeviceRequired,
1071 mIsStrongBoxBacked);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -07001072 }
1073 }
1074}