1 /*
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 
17 package android.security.keystore;
18 
19 import android.annotation.IntRange;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.TestApi;
23 import android.app.KeyguardManager;
24 import android.hardware.biometrics.BiometricManager;
25 import android.hardware.biometrics.BiometricPrompt;
26 import android.security.GateKeeper;
27 
28 import java.security.Key;
29 import java.security.KeyStore.ProtectionParameter;
30 import java.security.Signature;
31 import java.security.cert.Certificate;
32 import java.util.Date;
33 
34 import javax.crypto.Cipher;
35 import javax.crypto.Mac;
36 
37 /**
38  * Specification of how a key or key pair is secured when imported into the
39  * <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)
42  * with what parameters (e.g., only with a particular padding scheme or digest), and the key's
43  * 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.
45  *
46  * <p>To import a key or key pair into the Android Keystore, create an instance of this class using
47  * 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  *
50  * <p>To obtain the secret/symmetric or private key from the Android Keystore use
51  * {@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)}.
53  * To obtain the public key from the Android Keystore use
54  * {@link java.security.KeyStore#getCertificate(String)} and then
55  * {@link Certificate#getPublicKey()}.
56  *
57  * <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.
64  *
65  * <p>Instances of this class are immutable.
66  *
67  * <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  *
77  * <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
79  * {@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.
81  * <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)
90  *                 .setBlockMode(KeyProperties.BLOCK_MODE_GCM)
91  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
92  *                 .build());
93  * // Key imported, obtain a reference to it.
94  * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
95  * // The original key can now be discarded.
96  *
97  * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
98  * cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
99  * ...
100  * }</pre>
101  *
102  * <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
127  * 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.
130  * <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)
141  *                 .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
157  * the last ten minutes. The use of the public key is unrestricted (see Known Issues). Both the
158  * 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)
171  *                 .setDigests(KeyProperties.DIGEST_SHA256)
172  *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
173  *                 // 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();
181  * // 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  * ...
215  * }</pre>
216  */
217 public final class KeyProtection implements ProtectionParameter, UserAuthArgs {
218     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;
228     private final @KeyProperties.AuthEnum int mUserAuthenticationType;
229     private final int mUserAuthenticationValidityDurationSeconds;
230     private final boolean mUserPresenceRequred;
231     private final boolean mUserAuthenticationValidWhileOnBody;
232     private final boolean mInvalidatedByBiometricEnrollment;
233     private final long mBoundToSecureUserId;
234     private final boolean mCriticalToDeviceEncryption;
235     private final boolean mUserConfirmationRequired;
236     private final boolean mUnlockedDeviceRequired;
237     private final boolean mIsStrongBoxBacked;
238 
KeyProtection( Date keyValidityStart, Date keyValidityForOriginationEnd, Date keyValidityForConsumptionEnd, @KeyProperties.PurposeEnum int purposes, @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings, @KeyProperties.SignaturePaddingEnum String[] signaturePaddings, @KeyProperties.DigestEnum String[] digests, @KeyProperties.BlockModeEnum String[] blockModes, boolean randomizedEncryptionRequired, boolean userAuthenticationRequired, @KeyProperties.AuthEnum int userAuthenticationType, int userAuthenticationValidityDurationSeconds, boolean userPresenceRequred, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment, long boundToSecureUserId, boolean criticalToDeviceEncryption, boolean userConfirmationRequired, boolean unlockedDeviceRequired, boolean isStrongBoxBacked)239     private KeyProtection(
240             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,
250             @KeyProperties.AuthEnum int userAuthenticationType,
251             int userAuthenticationValidityDurationSeconds,
252             boolean userPresenceRequred,
253             boolean userAuthenticationValidWhileOnBody,
254             boolean invalidatedByBiometricEnrollment,
255             long boundToSecureUserId,
256             boolean criticalToDeviceEncryption,
257             boolean userConfirmationRequired,
258             boolean unlockedDeviceRequired,
259             boolean isStrongBoxBacked) {
260         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
261         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
262         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
263         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;
272         mUserAuthenticationType = userAuthenticationType;
273         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
274         mUserPresenceRequred = userPresenceRequred;
275         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
276         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
277         mBoundToSecureUserId = boundToSecureUserId;
278         mCriticalToDeviceEncryption = criticalToDeviceEncryption;
279         mUserConfirmationRequired = userConfirmationRequired;
280         mUnlockedDeviceRequired = unlockedDeviceRequired;
281         mIsStrongBoxBacked = isStrongBoxBacked;
282     }
283 
284     /**
285      * 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
getKeyValidityStart()290     public Date getKeyValidityStart() {
291         return Utils.cloneIfNotNull(mKeyValidityStart);
292     }
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
getKeyValidityForConsumptionEnd()300     public Date getKeyValidityForConsumptionEnd() {
301         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
302     }
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
getKeyValidityForOriginationEnd()310     public Date getKeyValidityForOriginationEnd() {
311         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
312     }
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      */
getPurposes()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
getEncryptionPaddings()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
getSignaturePaddings()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
getDigests()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      */
isDigestsSpecified()372     public boolean isDigestsSpecified() {
373         return mDigests != null;
374     }
375 
376     /**
377      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
378      * 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
getBlockModes()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      */
isRandomizedEncryptionRequired()397     public boolean isRandomizedEncryptionRequired() {
398         return mRandomizedEncryptionRequired;
399     }
400 
401     /**
402      * 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.
407      *
408      * @see #getUserAuthenticationValidityDurationSeconds()
409      * @see Builder#setUserAuthenticationRequired(boolean)
410      */
isUserAuthenticationRequired()411     public boolean isUserAuthenticationRequired() {
412         return mUserAuthenticationRequired;
413     }
414 
415     /**
416      * 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      */
isUserConfirmationRequired()431     public boolean isUserConfirmationRequired() {
432         return mUserConfirmationRequired;
433     }
434 
getUserAuthenticationType()435     public @KeyProperties.AuthEnum int getUserAuthenticationType() {
436         return mUserAuthenticationType;
437     }
438 
439     /**
440      * 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.
446      *
447      * @return duration in seconds or {@code -1} if authentication is required for every use of the
448      *         key.
449      *
450      * @see #isUserAuthenticationRequired()
451      * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
452      */
getUserAuthenticationValidityDurationSeconds()453     public int getUserAuthenticationValidityDurationSeconds() {
454         return mUserAuthenticationValidityDurationSeconds;
455     }
456 
457     /**
458      * 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.
460      * 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
462      * 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.
468      */
isUserPresenceRequired()469     public boolean isUserPresenceRequired() {
470         return mUserPresenceRequred;
471     }
472 
473     /**
474      * 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.
477      *
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      */
isUserAuthenticationValidWhileOnBody()485     public boolean isUserAuthenticationValidWhileOnBody() {
486         return mUserAuthenticationValidWhileOnBody;
487     }
488 
489     /**
490      * 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.
493      *
494      * @see #isUserAuthenticationRequired()
495      * @see #getUserAuthenticationValidityDurationSeconds()
496      * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
497      */
isInvalidatedByBiometricEnrollment()498     public boolean isInvalidatedByBiometricEnrollment() {
499         return mInvalidatedByBiometricEnrollment;
500     }
501 
502     /**
503      * 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
507      * id of the current biometric set for keys requiring explicit biometric authorization).
508      * 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      */
516     @TestApi
getBoundToSpecificSecureUserId()517     public long getBoundToSpecificSecureUserId() {
518         return mBoundToSecureUserId;
519     }
520 
521     /**
522      * 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      */
isCriticalToDeviceEncryption()527     public boolean isCriticalToDeviceEncryption() {
528         return mCriticalToDeviceEncryption;
529     }
530 
531     /**
532      * 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
534      * locked.
535      *
536      * @see Builder#setUnlockedDeviceRequired(boolean)
537      */
isUnlockedDeviceRequired()538     public boolean isUnlockedDeviceRequired() {
539         return mUnlockedDeviceRequired;
540     }
541 
542     /**
543      * Returns {@code true} if the key is protected by a Strongbox security chip.
544      * @hide
545      */
isStrongBoxBacked()546     public boolean isStrongBoxBacked() {
547         return mIsStrongBoxBacked;
548     }
549 
550     /**
551      * Builder of {@link KeyProtection} instances.
552      */
553     public final static class Builder {
554         private @KeyProperties.PurposeEnum int mPurposes;
555 
556         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;
565         private int mUserAuthenticationValidityDurationSeconds = 0;
566         private @KeyProperties.AuthEnum int mUserAuthenticationType =
567                 KeyProperties.AUTH_BIOMETRIC_STRONG;
568         private boolean mUserPresenceRequired = false;
569         private boolean mUserAuthenticationValidWhileOnBody;
570         private boolean mInvalidatedByBiometricEnrollment = true;
571         private boolean mUserConfirmationRequired;
572         private boolean mUnlockedDeviceRequired = false;
573 
574         private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID;
575         private boolean mCriticalToDeviceEncryption = false;
576         private boolean mIsStrongBoxBacked = false;
577 
578         /**
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          *
584          *        <p>See {@link KeyProperties}.{@code PURPOSE} flags.
585          */
Builder(@eyProperties.PurposeEnum int purposes)586         public Builder(@KeyProperties.PurposeEnum int purposes) {
587             mPurposes = purposes;
588         }
589 
590         /**
591          * 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          *
595          * @see #setKeyValidityEnd(Date)
596          */
597         @NonNull
setKeyValidityStart(Date startDate)598         public Builder setKeyValidityStart(Date startDate) {
599             mKeyValidityStart = Utils.cloneIfNotNull(startDate);
600             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          *
608          * @see #setKeyValidityStart(Date)
609          * @see #setKeyValidityForConsumptionEnd(Date)
610          * @see #setKeyValidityForOriginationEnd(Date)
611          */
612         @NonNull
setKeyValidityEnd(Date endDate)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          *
624          * @see #setKeyValidityForConsumptionEnd(Date)
625          */
626         @NonNull
setKeyValidityForOriginationEnd(Date endDate)627         public Builder setKeyValidityForOriginationEnd(Date endDate) {
628             mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
629             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          *
638          * @see #setKeyValidityForOriginationEnd(Date)
639          */
640         @NonNull
setKeyValidityForConsumptionEnd(Date endDate)641         public Builder setKeyValidityForConsumptionEnd(Date endDate) {
642             mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
643             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          *
653          * <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
655          * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
656          * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
657          * required by some cipher suites, and some stacks request decryption using no padding
658          * whereas others request PKCS#1 padding.
659          *
660          * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
661          */
662         @NonNull
setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)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          *
676          * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
677          */
678         @NonNull
setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)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
687          * key can be used. Attempts to use the key with any other digest algorithm will be
688          * rejected.
689          *
690          * <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.,
693          * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
694          * for more than one digest.
695          *
696          * <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          *
701          * <p>See {@link KeyProperties}.{@code DIGEST} constants.
702          */
703         @NonNull
setDigests(@eyProperties.DigestEnum String... digests)704         public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
705             mDigests = ArrayUtils.cloneIfNotEmpty(digests);
706             return this;
707         }
708 
709         /**
710          * 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.
713          *
714          * <p>This must be specified for symmetric encryption/decryption keys.
715          *
716          * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
717          */
718         @NonNull
setBlockModes(@eyProperties.BlockModeEnum String... blockModes)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>
739          * <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
741          * 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>
757          */
758         @NonNull
setRandomizedEncryptionRequired(boolean required)759         public Builder setRandomizedEncryptionRequired(boolean required) {
760             mRandomizedEncryptionRequired = required;
761             return this;
762         }
763 
764         /**
765          * Sets whether this key is authorized to be used only if the user has been authenticated.
766          *
767          * <p>By default, the key is authorized to be used regardless of whether the user has been
768          * authenticated.
769          *
770          * <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
775          * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
776          * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
777          * <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
779          * password/PIN/pattern or biometric.
780          * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
781          * information</a>.
782          * <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
786          * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
787          * no more biometrics are enrolled, unless {@link
788          * #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>
791          *
792          * <p>This authorization applies only to secret key and private key operations. Public key
793          * operations are not restricted.
794          *
795          * @see #setUserAuthenticationValidityDurationSeconds(int)
796          * @see KeyguardManager#isDeviceSecure()
797          * @see BiometricManager#canAuthenticate()
798          */
799         @NonNull
setUserAuthenticationRequired(boolean required)800         public Builder setUserAuthenticationRequired(boolean required) {
801             mUserAuthenticationRequired = required;
802             return this;
803         }
804 
805         /**
806          * 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          *
819          * See {@link android.security.ConfirmationPrompt} class for
820          * more details about user confirmations.
821          */
822         @NonNull
setUserConfirmationRequired(boolean required)823         public Builder setUserConfirmationRequired(boolean required) {
824             mUserConfirmationRequired = required;
825             return this;
826         }
827 
828         /**
829          * 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)}).
832          *
833          * <p>By default, if user authentication is required, it must take place for every use of
834          * the key.
835          *
836          * <p>Cryptographic operations involving keys which require user authentication to take
837          * place for every operation can only use biometric authentication. This is achieved by
838          * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
839          * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
840          * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
841          * 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.
857          *
858          * @see #setUserAuthenticationRequired(boolean)
859          * @see BiometricPrompt
860          * @see BiometricPrompt.CryptoObject
861          * @see KeyguardManager
862          * @deprecated See {@link #setUserAuthenticationParameters(int, int)}
863          */
864         @Deprecated
865         @NonNull
setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)866         public Builder setUserAuthenticationValidityDurationSeconds(
867                 @IntRange(from = -1) int seconds) {
868             if (seconds < -1) {
869                 throw new IllegalArgumentException("seconds must be -1 or larger");
870             }
871             if (seconds == -1) {
872                 return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
873             }
874             return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL
875                                                             | KeyProperties.AUTH_BIOMETRIC_STRONG);
876         }
877 
878         /**
879          * Sets the duration of time (seconds) and authorization type for which this key is
880          * authorized to be used after the user is successfully authenticated. This has effect if
881          * the key requires user authentication for its use (see
882          * {@link #setUserAuthenticationRequired(boolean)}).
883          *
884          * <p>By default, if user authentication is required, it must take place for every use of
885          * the key.
886          *
887          * <p>These cryptographic operations will throw {@link UserNotAuthenticatedException} during
888          * initialization if the user needs to be authenticated to proceed. This situation can be
889          * resolved by the user authenticating with the appropriate biometric or credential as
890          * required by the key. See {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)}
891          * and {@link BiometricManager.Authenticators}.
892          *
893          * <p>Once resolved, initializing a new cryptographic operation using this key (or any other
894          * key which is authorized to be used for a fixed duration of time after user
895          * authentication) should succeed provided the user authentication flow completed
896          * successfully.
897          *
898          * @param timeout duration in seconds or {@code 0} if user authentication must take place
899          *        for every use of the key.
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
setUserAuthenticationParameters(@ntRangefrom = 0) int timeout, @KeyProperties.AuthEnum int type)909         public Builder setUserAuthenticationParameters(@IntRange(from = 0) int timeout,
910                                                        @KeyProperties.AuthEnum int type) {
911             if (timeout < 0) {
912                 throw new IllegalArgumentException("timeout must be 0 or larger");
913             }
914             mUserAuthenticationValidityDurationSeconds = timeout;
915             mUserAuthenticationType = type;
916             return this;
917         }
918 
919         /**
920          * Sets whether a test of user presence is required to be performed between the
921          * {@code Signature.initSign()} and {@code Signature.sign()} method calls. It requires that
922          * the KeyStore implementation have a direct way to validate the user presence for example
923          * a KeyStore hardware backed strongbox can use a button press that is observable in
924          * hardware. A test for user presence is tangential to authentication. The test can be part
925          * of an authentication step as long as this step can be validated by the hardware
926          * protecting the key and cannot be spoofed. For example, a physical button press can be
927          * used as a test of user presence if the other pins connected to the button are not able
928          * to simulate a button press. There must be no way for the primary processor to fake a
929          * button press, or that button must not be used as a test of user presence.
930          */
931         @NonNull
setUserPresenceRequired(boolean required)932         public Builder setUserPresenceRequired(boolean required) {
933             mUserPresenceRequired = required;
934             return this;
935         }
936 
937         /**
938          * Sets whether the key will remain authorized only until the device is removed from the
939          * user's body up to the limit of the authentication validity period (see
940          * {@link #setUserAuthenticationValidityDurationSeconds} and
941          * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
942          * user's body, the key will be considered unauthorized and the user will need to
943          * re-authenticate to use it. For keys without an authentication validity period this
944          * parameter has no effect.
945          *
946          * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
947          * effect; the device will always be considered to be "on-body" and the key will therefore
948          * remain authorized until the validity period ends.
949          *
950          * @param remainsValid if {@code true}, and if the device supports on-body detection, key
951          * will be invalidated when the device is removed from the user's body or when the
952          * authentication validity expires, whichever occurs first.
953          */
954         @NonNull
setUserAuthenticationValidWhileOnBody(boolean remainsValid)955         public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
956             mUserAuthenticationValidWhileOnBody = remainsValid;
957             return this;
958         }
959 
960         /**
961          * Sets whether this key should be invalidated on biometric enrollment.  This
962          * applies only to keys which require user authentication (see {@link
963          * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
964          * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
965          * valid for biometric authentication only.
966          *
967          * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
968          * biometric authentication only are <em>irreversibly invalidated</em> when a new
969          * biometric is enrolled, or when all existing biometrics are deleted.  That may be
970          * changed by calling this method with {@code invalidateKey} set to {@code false}.
971          *
972          * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
973          * improves security by ensuring that an unauthorized person who obtains the password can't
974          * gain the use of biometric-authenticated keys by enrolling their own biometric.  However,
975          * invalidating keys makes key-dependent operations impossible, requiring some fallback
976          * procedure to authenticate the user and set up a new key.
977          */
978         @NonNull
setInvalidatedByBiometricEnrollment(boolean invalidateKey)979         public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
980             mInvalidatedByBiometricEnrollment = invalidateKey;
981             return this;
982         }
983 
984         /**
985          * Set the secure user id that this key should be bound to.
986          *
987          * Normally an authentication-bound key is tied to the secure user id of the current user
988          * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the
989          * authenticator id of the current biometric set for keys requiring explicit biometric
990          * authorization). If this parameter is set (this method returning non-zero value), the key
991          * should be tied to the specified secure user id, overriding the logic above.
992          *
993          * This is only applicable when {@link #setUserAuthenticationRequired} is set to
994          * {@code true}
995          *
996          * @see KeyProtection#getBoundToSpecificSecureUserId()
997          * @hide
998          */
999         @TestApi
setBoundToSpecificSecureUserId(long secureUserId)1000         public Builder setBoundToSpecificSecureUserId(long secureUserId) {
1001             mBoundToSecureUserId = secureUserId;
1002             return this;
1003         }
1004 
1005         /**
1006          * Set whether this key is critical to the device encryption flow
1007          *
1008          * This is a special flag only available to system servers to indicate the current key
1009          * is part of the device encryption flow.
1010          *
1011          * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
1012          * @hide
1013          */
setCriticalToDeviceEncryption(boolean critical)1014         public Builder setCriticalToDeviceEncryption(boolean critical) {
1015             mCriticalToDeviceEncryption = critical;
1016             return this;
1017         }
1018 
1019         /**
1020          * Sets whether the keystore requires the screen to be unlocked before allowing decryption
1021          * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
1022          * key while the screen is locked will fail. A locked device requires a PIN, password,
1023          * biometric, or other trusted factor to access. While the screen is locked, the key can
1024          * still be used for encryption or signature verification.
1025          */
1026         @NonNull
setUnlockedDeviceRequired(boolean unlockedDeviceRequired)1027         public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
1028             mUnlockedDeviceRequired = unlockedDeviceRequired;
1029             return this;
1030         }
1031 
1032         /**
1033          * Sets whether this key should be protected by a StrongBox security chip.
1034          * @hide
1035          */
1036         @NonNull
setIsStrongBoxBacked(boolean isStrongBoxBacked)1037         public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
1038             mIsStrongBoxBacked = isStrongBoxBacked;
1039             return this;
1040         }
1041 
1042         /**
1043          * Builds an instance of {@link KeyProtection}.
1044          *
1045          * @throws IllegalArgumentException if a required field is missing
1046          */
1047         @NonNull
build()1048         public KeyProtection build() {
1049             return new KeyProtection(
1050                     mKeyValidityStart,
1051                     mKeyValidityForOriginationEnd,
1052                     mKeyValidityForConsumptionEnd,
1053                     mPurposes,
1054                     mEncryptionPaddings,
1055                     mSignaturePaddings,
1056                     mDigests,
1057                     mBlockModes,
1058                     mRandomizedEncryptionRequired,
1059                     mUserAuthenticationRequired,
1060                     mUserAuthenticationType,
1061                     mUserAuthenticationValidityDurationSeconds,
1062                     mUserPresenceRequired,
1063                     mUserAuthenticationValidWhileOnBody,
1064                     mInvalidatedByBiometricEnrollment,
1065                     mBoundToSecureUserId,
1066                     mCriticalToDeviceEncryption,
1067                     mUserConfirmationRequired,
1068                     mUnlockedDeviceRequired,
1069                     mIsStrongBoxBacked);
1070         }
1071     }
1072 }
1073