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 import android.security.keystore2.KeymasterUtils;
28 
29 import java.security.Key;
30 import java.security.KeyStore.ProtectionParameter;
31 import java.security.Signature;
32 import java.security.cert.Certificate;
33 import java.util.Date;
34 
35 import javax.crypto.Cipher;
36 import javax.crypto.Mac;
37 
38 /**
39  * Specification of how a key or key pair is secured when imported into the
40  * <a href="{@docRoot}training/articles/keystore.html">Android Keystore system</a>. This class
41  * specifies authorized uses of the imported key, such as whether user authentication is required
42  * for using the key, what operations the key is authorized for (e.g., decryption, but not signing)
43  * with what parameters (e.g., only with a particular padding scheme or digest), and the key's
44  * validity start and end dates. Key use authorizations expressed in this class apply only to secret
45  * keys and private keys -- public keys can be used for any supported operations.
46  *
47  * <p>To import a key or key pair into the Android Keystore, create an instance of this class using
48  * the {@link Builder} and pass the instance into {@link java.security.KeyStore#setEntry(String, java.security.KeyStore.Entry, ProtectionParameter) KeyStore.setEntry}
49  * with the key or key pair being imported.
50  *
51  * <p>To obtain the secret/symmetric or private key from the Android Keystore use
52  * {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)} or
53  * {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
54  * To obtain the public key from the Android Keystore use
55  * {@link java.security.KeyStore#getCertificate(String)} and then
56  * {@link Certificate#getPublicKey()}.
57  *
58  * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
59  * Keystore, its private keys implement {@link java.security.interfaces.ECKey} or
60  * {@link java.security.interfaces.RSAKey} interfaces whereas its public keys implement
61  * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
62  * interfaces.
63  *
64  * <p>NOTE: The key material of keys stored in the Android Keystore is not accessible.
65  *
66  * <p>Instances of this class are immutable.
67  *
68  * <p><h3>Known issues</h3>
69  * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be
70  * enforced even for public keys. To work around this issue extract the public key material to use
71  * outside of Android Keystore. For example:
72  * <pre> {@code
73  * PublicKey unrestrictedPublicKey =
74  *         KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
75  *                 new X509EncodedKeySpec(publicKey.getEncoded()));
76  * }</pre>
77  *
78  * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
79  * This example illustrates how to import an AES key into the Android KeyStore under alias
80  * {@code key1} authorized to be used only for encryption/decryption in GCM mode with no padding.
81  * The key must export its key material via {@link Key#getEncoded()} in {@code RAW} format.
82  * <pre> {@code
83  * SecretKey key = ...; // AES key
84  *
85  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
86  * keyStore.load(null);
87  * keyStore.setEntry(
88  *         "key1",
89  *         new KeyStore.SecretKeyEntry(key),
90  *         new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
91  *                 .setBlockMode(KeyProperties.BLOCK_MODE_GCM)
92  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
93  *                 .build());
94  * // Key imported, obtain a reference to it.
95  * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
96  * // The original key can now be discarded.
97  *
98  * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
99  * cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
100  * ...
101  * }</pre>
102  *
103  * <p><h3>Example: HMAC key for generating MACs using SHA-512</h3>
104  * This example illustrates how to import an HMAC key into the Android KeyStore under alias
105  * {@code key1} authorized to be used only for generating MACs using SHA-512 digest. The key must
106  * export its key material via {@link Key#getEncoded()} in {@code RAW} format.
107  * <pre> {@code
108  * SecretKey key = ...; // HMAC key of algorithm "HmacSHA512".
109  *
110  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
111  * keyStore.load(null);
112  * keyStore.setEntry(
113  *         "key1",
114  *         new KeyStore.SecretKeyEntry(key),
115  *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());
116  * // Key imported, obtain a reference to it.
117  * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
118  * // The original key can now be discarded.
119  *
120  * Mac mac = Mac.getInstance("HmacSHA512");
121  * mac.init(keyStoreKey);
122  * ...
123  * }</pre>
124  *
125  * <p><h3>Example: EC key pair for signing/verification using ECDSA</h3>
126  * This example illustrates how to import an EC key pair into the Android KeyStore under alias
127  * {@code key2} with the private key authorized to be used only for signing with SHA-256 or SHA-512
128  * digests. The use of the public key is unrestricted. Both the private and the public key must
129  * export their key material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format
130  * respectively.
131  * <pre> {@code
132  * PrivateKey privateKey = ...;   // EC private key
133  * Certificate[] certChain = ...; // Certificate chain with the first certificate
134  *                                // containing the corresponding EC public key.
135  *
136  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
137  * keyStore.load(null);
138  * keyStore.setEntry(
139  *         "key2",
140  *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
141  *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
142  *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
143  *                 .build());
144  * // Key pair imported, obtain a reference to it.
145  * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
146  * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
147  * // The original private key can now be discarded.
148  *
149  * Signature signature = Signature.getInstance("SHA256withECDSA");
150  * signature.initSign(keyStorePrivateKey);
151  * ...
152  * }</pre>
153  *
154  * <p><h3>Example: RSA key pair for signing/verification using PKCS#1 padding</h3>
155  * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
156  * {@code key2} with the private key authorized to be used only for signing using the PKCS#1
157  * signature padding scheme with SHA-256 digest and only if the user has been authenticated within
158  * the last ten minutes. The use of the public key is unrestricted (see Known Issues). Both the
159  * private and the public key must export their key material via {@link Key#getEncoded()} in
160  * {@code PKCS#8} and {@code X.509} format respectively.
161  * <pre> {@code
162  * PrivateKey privateKey = ...;   // RSA private key
163  * Certificate[] certChain = ...; // Certificate chain with the first certificate
164  *                                // containing the corresponding RSA public key.
165  *
166  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
167  * keyStore.load(null);
168  * keyStore.setEntry(
169  *         "key2",
170  *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
171  *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
172  *                 .setDigests(KeyProperties.DIGEST_SHA256)
173  *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
174  *                 // Only permit this key to be used if the user
175  *                 // authenticated within the last ten minutes.
176  *                 .setUserAuthenticationRequired(true)
177  *                 .setUserAuthenticationValidityDurationSeconds(10 * 60)
178  *                 .build());
179  * // Key pair imported, obtain a reference to it.
180  * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
181  * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
182  * // The original private key can now be discarded.
183  *
184  * Signature signature = Signature.getInstance("SHA256withRSA");
185  * signature.initSign(keyStorePrivateKey);
186  * ...
187  * }</pre>
188  *
189  * <p><h3>Example: RSA key pair for encryption/decryption using PKCS#1 padding</h3>
190  * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
191  * {@code key2} with the private key authorized to be used only for decryption using the PKCS#1
192  * encryption padding scheme. The use of public key is unrestricted, thus permitting encryption
193  * using any padding schemes and digests. Both the private and the public key must export their key
194  * material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format respectively.
195  * <pre> {@code
196  * PrivateKey privateKey = ...;   // RSA private key
197  * Certificate[] certChain = ...; // Certificate chain with the first certificate
198  *                                // containing the corresponding RSA public key.
199  *
200  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
201  * keyStore.load(null);
202  * keyStore.setEntry(
203  *         "key2",
204  *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
205  *         new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
206  *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
207  *                 .build());
208  * // Key pair imported, obtain a reference to it.
209  * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
210  * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
211  * // The original private key can now be discarded.
212  *
213  * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
214  * cipher.init(Cipher.DECRYPT_MODE, keyStorePrivateKey);
215  * ...
216  * }</pre>
217  */
218 public final class KeyProtection implements ProtectionParameter, UserAuthArgs {
219     private final Date mKeyValidityStart;
220     private final Date mKeyValidityForOriginationEnd;
221     private final Date mKeyValidityForConsumptionEnd;
222     private final @KeyProperties.PurposeEnum int mPurposes;
223     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
224     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
225     private final @KeyProperties.DigestEnum String[] mDigests;
226     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
227     private final boolean mRandomizedEncryptionRequired;
228     private final boolean mUserAuthenticationRequired;
229     private final @KeyProperties.AuthEnum int mUserAuthenticationType;
230     private final int mUserAuthenticationValidityDurationSeconds;
231     private final boolean mUserPresenceRequred;
232     private final boolean mUserAuthenticationValidWhileOnBody;
233     private final boolean mInvalidatedByBiometricEnrollment;
234     private final long mBoundToSecureUserId;
235     private final boolean mCriticalToDeviceEncryption;
236     private final boolean mUserConfirmationRequired;
237     private final boolean mUnlockedDeviceRequired;
238     private final boolean mIsStrongBoxBacked;
239     private final int mMaxUsageCount;
240     private final boolean mRollbackResistant;
241 
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, int maxUsageCount, boolean rollbackResistant)242     private KeyProtection(
243             Date keyValidityStart,
244             Date keyValidityForOriginationEnd,
245             Date keyValidityForConsumptionEnd,
246             @KeyProperties.PurposeEnum int purposes,
247             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
248             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
249             @KeyProperties.DigestEnum String[] digests,
250             @KeyProperties.BlockModeEnum String[] blockModes,
251             boolean randomizedEncryptionRequired,
252             boolean userAuthenticationRequired,
253             @KeyProperties.AuthEnum int userAuthenticationType,
254             int userAuthenticationValidityDurationSeconds,
255             boolean userPresenceRequred,
256             boolean userAuthenticationValidWhileOnBody,
257             boolean invalidatedByBiometricEnrollment,
258             long boundToSecureUserId,
259             boolean criticalToDeviceEncryption,
260             boolean userConfirmationRequired,
261             boolean unlockedDeviceRequired,
262             boolean isStrongBoxBacked,
263             int maxUsageCount,
264             boolean rollbackResistant) {
265         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
266         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
267         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
268         mPurposes = purposes;
269         mEncryptionPaddings =
270                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
271         mSignaturePaddings =
272                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
273         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
274         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
275         mRandomizedEncryptionRequired = randomizedEncryptionRequired;
276         mUserAuthenticationRequired = userAuthenticationRequired;
277         mUserAuthenticationType = userAuthenticationType;
278         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
279         mUserPresenceRequred = userPresenceRequred;
280         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
281         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
282         mBoundToSecureUserId = boundToSecureUserId;
283         mCriticalToDeviceEncryption = criticalToDeviceEncryption;
284         mUserConfirmationRequired = userConfirmationRequired;
285         mUnlockedDeviceRequired = unlockedDeviceRequired;
286         mIsStrongBoxBacked = isStrongBoxBacked;
287         mMaxUsageCount = maxUsageCount;
288         mRollbackResistant = rollbackResistant;
289     }
290 
291     /**
292      * Gets the time instant before which the key is not yet valid.
293      *
294      * @return instant or {@code null} if not restricted.
295      */
296     @Nullable
getKeyValidityStart()297     public Date getKeyValidityStart() {
298         return Utils.cloneIfNotNull(mKeyValidityStart);
299     }
300 
301     /**
302      * Gets the time instant after which the key is no long valid for decryption and verification.
303      *
304      * @return instant or {@code null} if not restricted.
305      */
306     @Nullable
getKeyValidityForConsumptionEnd()307     public Date getKeyValidityForConsumptionEnd() {
308         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
309     }
310 
311     /**
312      * Gets the time instant after which the key is no long valid for encryption and signing.
313      *
314      * @return instant or {@code null} if not restricted.
315      */
316     @Nullable
getKeyValidityForOriginationEnd()317     public Date getKeyValidityForOriginationEnd() {
318         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
319     }
320 
321     /**
322      * Gets the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
323      * Attempts to use the key for any other purpose will be rejected.
324      *
325      * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
326      */
getPurposes()327     public @KeyProperties.PurposeEnum int getPurposes() {
328         return mPurposes;
329     }
330 
331     /**
332      * Gets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code PKCS1Padding},
333      * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to use
334      * the key with any other padding scheme will be rejected.
335      *
336      * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
337      */
338     @NonNull
getEncryptionPaddings()339     public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
340         return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
341     }
342 
343     /**
344      * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
345      * can be used when signing/verifying. Attempts to use the key with any other padding scheme
346      * will be rejected.
347      *
348      * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
349      */
350     @NonNull
getSignaturePaddings()351     public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
352         return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
353     }
354 
355     /**
356      * Gets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the key
357      * can be used.
358      *
359      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
360      *
361      * @throws IllegalStateException if this set has not been specified.
362      *
363      * @see #isDigestsSpecified()
364      */
365     @NonNull
getDigests()366     public @KeyProperties.DigestEnum String[] getDigests() {
367         if (mDigests == null) {
368             throw new IllegalStateException("Digests not specified");
369         }
370         return ArrayUtils.cloneIfNotEmpty(mDigests);
371     }
372 
373     /**
374      * Returns {@code true} if the set of digest algorithms with which the key can be used has been
375      * specified.
376      *
377      * @see #getDigests()
378      */
isDigestsSpecified()379     public boolean isDigestsSpecified() {
380         return mDigests != null;
381     }
382 
383     /**
384      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
385      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
386      * rejected.
387      *
388      * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
389      */
390     @NonNull
getBlockModes()391     public @KeyProperties.BlockModeEnum String[] getBlockModes() {
392         return ArrayUtils.cloneIfNotEmpty(mBlockModes);
393     }
394 
395     /**
396      * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
397      * different ciphertexts for the same plaintext every time. The formal cryptographic property
398      * being required is <em>indistinguishability under chosen-plaintext attack ({@code
399      * IND-CPA})</em>. This property is important because it mitigates several classes of
400      * weaknesses due to which ciphertext may leak information about plaintext. For example, if a
401      * given plaintext always produces the same ciphertext, an attacker may see the repeated
402      * ciphertexts and be able to deduce something about the plaintext.
403      */
isRandomizedEncryptionRequired()404     public boolean isRandomizedEncryptionRequired() {
405         return mRandomizedEncryptionRequired;
406     }
407 
408     /**
409      * Returns {@code true} if the key is authorized to be used only if the user has been
410      * authenticated.
411      *
412      * <p>This authorization applies only to secret key and private key operations. Public key
413      * operations are not restricted.
414      *
415      * @see #getUserAuthenticationValidityDurationSeconds()
416      * @see Builder#setUserAuthenticationRequired(boolean)
417      */
isUserAuthenticationRequired()418     public boolean isUserAuthenticationRequired() {
419         return mUserAuthenticationRequired;
420     }
421 
422     /**
423      * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
424      * user.
425      *
426      * Confirmation is separate from user authentication (see
427      * {@link #isUserAuthenticationRequired()}). Keys can be created that require confirmation but
428      * not user authentication, or user authentication but not confirmation, or both. Confirmation
429      * verifies that some user with physical possession of the device has approved a displayed
430      * message. User authentication verifies that the correct user is present and has
431      * authenticated.
432      *
433      * <p>This authorization applies only to secret key and private key operations. Public key
434      * operations are not restricted.
435      *
436      * @see Builder#setUserConfirmationRequired(boolean)
437      */
isUserConfirmationRequired()438     public boolean isUserConfirmationRequired() {
439         return mUserConfirmationRequired;
440     }
441 
getUserAuthenticationType()442     public @KeyProperties.AuthEnum int getUserAuthenticationType() {
443         return mUserAuthenticationType;
444     }
445 
446     /**
447      * Gets the duration of time (seconds) for which this key is authorized to be used after the
448      * user is successfully authenticated. This has effect only if user authentication is required
449      * (see {@link #isUserAuthenticationRequired()}).
450      *
451      * <p>This authorization applies only to secret key and private key operations. Public key
452      * operations are not restricted.
453      *
454      * @return duration in seconds or {@code -1} if authentication is required for every use of the
455      *         key.
456      *
457      * @see #isUserAuthenticationRequired()
458      * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
459      */
getUserAuthenticationValidityDurationSeconds()460     public int getUserAuthenticationValidityDurationSeconds() {
461         return mUserAuthenticationValidityDurationSeconds;
462     }
463 
464     /**
465      * Returns {@code true} if the key is authorized to be used only if a test of user presence has
466      * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls.
467      * It requires that the KeyStore implementation have a direct way to validate the user presence
468      * for example a KeyStore hardware backed strongbox can use a button press that is observable
469      * in hardware. A test for user presence is tangential to authentication. The test can be part
470      * of an authentication step as long as this step can be validated by the hardware protecting
471      * the key and cannot be spoofed. For example, a physical button press can be used as a test of
472      * user presence if the other pins connected to the button are not able to simulate a button
473      * press. There must be no way for the primary processor to fake a button press, or that
474      * button must not be used as a test of user presence.
475      */
isUserPresenceRequired()476     public boolean isUserPresenceRequired() {
477         return mUserPresenceRequred;
478     }
479 
480     /**
481      * Returns {@code true} if the key will be de-authorized when the device is removed from the
482      * user's body.  This option has no effect on keys that don't have an authentication validity
483      * duration, and has no effect if the device lacks an on-body sensor.
484      *
485      * <p>Authorization applies only to secret key and private key operations. Public key operations
486      * are not restricted.
487      *
488      * @see #isUserAuthenticationRequired()
489      * @see #getUserAuthenticationValidityDurationSeconds()
490      * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
491      */
isUserAuthenticationValidWhileOnBody()492     public boolean isUserAuthenticationValidWhileOnBody() {
493         return mUserAuthenticationValidWhileOnBody;
494     }
495 
496     /**
497      * Returns {@code true} if the key is irreversibly invalidated when a new biometric is
498      * enrolled or all enrolled biometrics are removed. This has effect only for keys that
499      * require biometric user authentication for every use.
500      *
501      * @see #isUserAuthenticationRequired()
502      * @see #getUserAuthenticationValidityDurationSeconds()
503      * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
504      */
isInvalidatedByBiometricEnrollment()505     public boolean isInvalidatedByBiometricEnrollment() {
506         return mInvalidatedByBiometricEnrollment;
507     }
508 
509     /**
510      * Return the secure user id that this key should be bound to.
511      *
512      * Normally an authentication-bound key is tied to the secure user id of the current user
513      * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the authenticator
514      * id of the current biometric set for keys requiring explicit biometric authorization).
515      * If this parameter is set (this method returning non-zero value), the key should be tied to
516      * the specified secure user id, overriding the logic above.
517      *
518      * This is only applicable when {@link #isUserAuthenticationRequired} is {@code true}
519      *
520      * @see KeymasterUtils#addUserAuthArgs
521      * @hide
522      */
523     @TestApi
getBoundToSpecificSecureUserId()524     public long getBoundToSpecificSecureUserId() {
525         return mBoundToSecureUserId;
526     }
527 
528     /**
529      * Return whether this key is critical to the device encryption flow.
530      *
531      * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
532      * @hide
533      */
isCriticalToDeviceEncryption()534     public boolean isCriticalToDeviceEncryption() {
535         return mCriticalToDeviceEncryption;
536     }
537 
538     /**
539      * Returns {@code true} if the screen must be unlocked for this key to be used for decryption or
540      * signing. Encryption and signature verification will still be available when the screen is
541      * locked.
542      *
543      * @see Builder#setUnlockedDeviceRequired(boolean)
544      */
isUnlockedDeviceRequired()545     public boolean isUnlockedDeviceRequired() {
546         return mUnlockedDeviceRequired;
547     }
548 
549     /**
550      * Returns {@code true} if the key is protected by a Strongbox security chip.
551      * @hide
552      */
isStrongBoxBacked()553     public boolean isStrongBoxBacked() {
554         return mIsStrongBoxBacked;
555     }
556 
557     /**
558      * Returns the maximum number of times the limited use key is allowed to be used or
559      * {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there’s no restriction on the number of
560      * times the key can be used.
561      *
562      * @see Builder#setMaxUsageCount(int)
563      */
getMaxUsageCount()564     public int getMaxUsageCount() {
565         return mMaxUsageCount;
566     }
567 
568     /**
569      * Returns {@code true} if the key is rollback-resistant, meaning that when deleted it is
570      * guaranteed to be permanently deleted and unusable.
571      *
572      * @see Builder#setRollbackResistant(boolean)
573      * @hide
574      */
isRollbackResistant()575     public boolean isRollbackResistant() {
576         return mRollbackResistant;
577     }
578 
579     /**
580      * Builder of {@link KeyProtection} instances.
581      */
582     public final static class Builder {
583         private @KeyProperties.PurposeEnum int mPurposes;
584 
585         private Date mKeyValidityStart;
586         private Date mKeyValidityForOriginationEnd;
587         private Date mKeyValidityForConsumptionEnd;
588         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
589         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
590         private @KeyProperties.DigestEnum String[] mDigests;
591         private @KeyProperties.BlockModeEnum String[] mBlockModes;
592         private boolean mRandomizedEncryptionRequired = true;
593         private boolean mUserAuthenticationRequired;
594         private int mUserAuthenticationValidityDurationSeconds = 0;
595         private @KeyProperties.AuthEnum int mUserAuthenticationType =
596                 KeyProperties.AUTH_BIOMETRIC_STRONG;
597         private boolean mUserPresenceRequired = false;
598         private boolean mUserAuthenticationValidWhileOnBody;
599         private boolean mInvalidatedByBiometricEnrollment = true;
600         private boolean mUserConfirmationRequired;
601         private boolean mUnlockedDeviceRequired = false;
602 
603         private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID;
604         private boolean mCriticalToDeviceEncryption = false;
605         private boolean mIsStrongBoxBacked = false;
606         private int mMaxUsageCount = KeyProperties.UNRESTRICTED_USAGE_COUNT;
607         private String mAttestKeyAlias = null;
608         private boolean mRollbackResistant = false;
609 
610         /**
611          * Creates a new instance of the {@code Builder}.
612          *
613          * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
614          *        used. Attempts to use the key for any other purpose will be rejected.
615          *
616          *        <p>See {@link KeyProperties}.{@code PURPOSE} flags.
617          */
Builder(@eyProperties.PurposeEnum int purposes)618         public Builder(@KeyProperties.PurposeEnum int purposes) {
619             mPurposes = purposes;
620         }
621 
622         /**
623          * Sets the time instant before which the key is not yet valid.
624          *
625          * <p>By default, the key is valid at any instant.
626          *
627          * @see #setKeyValidityEnd(Date)
628          */
629         @NonNull
setKeyValidityStart(Date startDate)630         public Builder setKeyValidityStart(Date startDate) {
631             mKeyValidityStart = Utils.cloneIfNotNull(startDate);
632             return this;
633         }
634 
635         /**
636          * Sets the time instant after which the key is no longer valid.
637          *
638          * <p>By default, the key is valid at any instant.
639          *
640          * @see #setKeyValidityStart(Date)
641          * @see #setKeyValidityForConsumptionEnd(Date)
642          * @see #setKeyValidityForOriginationEnd(Date)
643          */
644         @NonNull
setKeyValidityEnd(Date endDate)645         public Builder setKeyValidityEnd(Date endDate) {
646             setKeyValidityForOriginationEnd(endDate);
647             setKeyValidityForConsumptionEnd(endDate);
648             return this;
649         }
650 
651         /**
652          * Sets the time instant after which the key is no longer valid for encryption and signing.
653          *
654          * <p>By default, the key is valid at any instant.
655          *
656          * @see #setKeyValidityForConsumptionEnd(Date)
657          */
658         @NonNull
setKeyValidityForOriginationEnd(Date endDate)659         public Builder setKeyValidityForOriginationEnd(Date endDate) {
660             mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
661             return this;
662         }
663 
664         /**
665          * Sets the time instant after which the key is no longer valid for decryption and
666          * verification.
667          *
668          * <p>By default, the key is valid at any instant.
669          *
670          * @see #setKeyValidityForOriginationEnd(Date)
671          */
672         @NonNull
setKeyValidityForConsumptionEnd(Date endDate)673         public Builder setKeyValidityForConsumptionEnd(Date endDate) {
674             mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
675             return this;
676         }
677 
678         /**
679          * Sets the set of padding schemes (e.g., {@code OAEPPadding}, {@code PKCS7Padding},
680          * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to
681          * use the key with any other padding scheme will be rejected.
682          *
683          * <p>This must be specified for keys which are used for encryption/decryption.
684          *
685          * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
686          * is usually necessary to authorize the use of no/any padding
687          * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
688          * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
689          * required by some cipher suites, and some stacks request decryption using no padding
690          * whereas others request PKCS#1 padding.
691          *
692          * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
693          */
694         @NonNull
setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)695         public Builder setEncryptionPaddings(
696                 @KeyProperties.EncryptionPaddingEnum String... paddings) {
697             mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
698             return this;
699         }
700 
701         /**
702          * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
703          * can be used when signing/verifying. Attempts to use the key with any other padding scheme
704          * will be rejected.
705          *
706          * <p>This must be specified for RSA keys which are used for signing/verification.
707          *
708          * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
709          */
710         @NonNull
setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)711         public Builder setSignaturePaddings(
712                 @KeyProperties.SignaturePaddingEnum String... paddings) {
713             mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
714             return this;
715         }
716 
717         /**
718          * Sets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the
719          * key can be used. Attempts to use the key with any other digest algorithm will be
720          * rejected.
721          *
722          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
723          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
724          * HMAC keys, the default is the digest specified in {@link Key#getAlgorithm()} (e.g.,
725          * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
726          * for more than one digest.
727          *
728          * <p>For private keys used for TLS/SSL client or server authentication it is usually
729          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
730          * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
731          * a private key to sign it.
732          *
733          * <p>See {@link KeyProperties}.{@code DIGEST} constants.
734          */
735         @NonNull
setDigests(@eyProperties.DigestEnum String... digests)736         public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
737             mDigests = ArrayUtils.cloneIfNotEmpty(digests);
738             return this;
739         }
740 
741         /**
742          * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
743          * used when encrypting/decrypting. Attempts to use the key with any other block modes will
744          * be rejected.
745          *
746          * <p>This must be specified for symmetric encryption/decryption keys.
747          *
748          * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
749          */
750         @NonNull
setBlockModes(@eyProperties.BlockModeEnum String... blockModes)751         public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
752             mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
753             return this;
754         }
755 
756         /**
757          * Sets whether encryption using this key must be sufficiently randomized to produce
758          * different ciphertexts for the same plaintext every time. The formal cryptographic
759          * property being required is <em>indistinguishability under chosen-plaintext attack
760          * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
761          * of weaknesses due to which ciphertext may leak information about plaintext. For example,
762          * if a given plaintext always produces the same ciphertext, an attacker may see the
763          * repeated ciphertexts and be able to deduce something about the plaintext.
764          *
765          * <p>By default, {@code IND-CPA} is required.
766          *
767          * <p>When {@code IND-CPA} is required:
768          * <ul>
769          * <li>transformation which do not offer {@code IND-CPA}, such as symmetric ciphers using
770          * {@code ECB} mode or RSA encryption without padding, are prohibited;</li>
771          * <li>in transformations which use an IV, such as symmetric ciphers in {@code GCM},
772          * {@code CBC}, and {@code CTR} block modes, caller-provided IVs are rejected when
773          * encrypting, to ensure that only random IVs are used.</li>
774          *
775          * <p>Before disabling this requirement, consider the following approaches instead:
776          * <ul>
777          * <li>If you are generating a random IV for encryption and then initializing a {@code}
778          * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
779          * instead. This will occur if the {@code Cipher} is initialized for encryption without an
780          * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
781          * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
782          * random, such as the name of the file being encrypted, or transaction ID, or password,
783          * or a device identifier), consider changing your design to use a random IV which will then
784          * be provided in addition to the ciphertext to the entities which need to decrypt the
785          * ciphertext.</li>
786          * <li>If you are using RSA encryption without padding, consider switching to padding
787          * schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
788          * </ul>
789          */
790         @NonNull
setRandomizedEncryptionRequired(boolean required)791         public Builder setRandomizedEncryptionRequired(boolean required) {
792             mRandomizedEncryptionRequired = required;
793             return this;
794         }
795 
796         /**
797          * Sets whether this key is authorized to be used only if the user has been authenticated.
798          *
799          * <p>By default, the key is authorized to be used regardless of whether the user has been
800          * authenticated.
801          *
802          * <p>When user authentication is required:
803          * <ul>
804          * <li>The key can only be import if secure lock screen is set up (see
805          * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
806          * authentication takes place for every use of the key (see
807          * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
808          * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
809          * <li>The use of the key must be authorized by the user by authenticating to this Android
810          * device using a subset of their secure lock screen credentials such as
811          * password/PIN/pattern or biometric.
812          * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
813          * information</a>.
814          * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
815          * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
816          * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
817          * Additionally, if the key requires that user authentication takes place for every use of
818          * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
819          * no more biometrics are enrolled, unless {@link
820          * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
821          * enrollment. Attempts to initialize cryptographic operations using such keys will throw
822          * {@link KeyPermanentlyInvalidatedException}.</li> </ul>
823          *
824          * <p>This authorization applies only to secret key and private key operations. Public key
825          * operations are not restricted.
826          *
827          * @see #setUserAuthenticationValidityDurationSeconds(int)
828          * @see KeyguardManager#isDeviceSecure()
829          * @see BiometricManager#canAuthenticate()
830          */
831         @NonNull
setUserAuthenticationRequired(boolean required)832         public Builder setUserAuthenticationRequired(boolean required) {
833             mUserAuthenticationRequired = required;
834             return this;
835         }
836 
837         /**
838          * Sets whether this key is authorized to be used only for messages confirmed by the
839          * user.
840          *
841          * Confirmation is separate from user authentication (see
842          * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require
843          * confirmation but not user authentication, or user authentication but not confirmation,
844          * or both. Confirmation verifies that some user with physical possession of the device has
845          * approved a displayed message. User authentication verifies that the correct user is
846          * present and has authenticated.
847          *
848          * <p>This authorization applies only to secret key and private key operations. Public key
849          * operations are not restricted.
850          *
851          * See {@link android.security.ConfirmationPrompt} class for
852          * more details about user confirmations.
853          */
854         @NonNull
setUserConfirmationRequired(boolean required)855         public Builder setUserConfirmationRequired(boolean required) {
856             mUserConfirmationRequired = required;
857             return this;
858         }
859 
860         /**
861          * Sets the duration of time (seconds) for which this key is authorized to be used after the
862          * user is successfully authenticated. This has effect if the key requires user
863          * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
864          *
865          * <p>By default, if user authentication is required, it must take place for every use of
866          * the key.
867          *
868          * <p>Cryptographic operations involving keys which require user authentication to take
869          * place for every operation can only use biometric authentication. This is achieved by
870          * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
871          * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
872          * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
873          * the cryptographic operation only if the authentication flow succeeds.
874          *
875          * <p>Cryptographic operations involving keys which are authorized to be used for a duration
876          * of time after a successful user authentication event can only use secure lock screen
877          * authentication. These cryptographic operations will throw
878          * {@link UserNotAuthenticatedException} during initialization if the user needs to be
879          * authenticated to proceed. This situation can be resolved by the user unlocking the secure
880          * lock screen of the Android or by going through the confirm credential flow initiated by
881          * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
882          * Once resolved, initializing a new cryptographic operation using this key (or any other
883          * key which is authorized to be used for a fixed duration of time after user
884          * authentication) should succeed provided the user authentication flow completed
885          * successfully.
886          *
887          * @param seconds duration in seconds or {@code -1} if user authentication must take place
888          *        for every use of the key.
889          *
890          * @see #setUserAuthenticationRequired(boolean)
891          * @see BiometricPrompt
892          * @see BiometricPrompt.CryptoObject
893          * @see KeyguardManager
894          * @deprecated See {@link #setUserAuthenticationParameters(int, int)}
895          */
896         @Deprecated
897         @NonNull
setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)898         public Builder setUserAuthenticationValidityDurationSeconds(
899                 @IntRange(from = -1) int seconds) {
900             if (seconds < -1) {
901                 throw new IllegalArgumentException("seconds must be -1 or larger");
902             }
903             if (seconds == -1) {
904                 return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
905             }
906             return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL
907                                                             | KeyProperties.AUTH_BIOMETRIC_STRONG);
908         }
909 
910         /**
911          * Sets the duration of time (seconds) and authorization type for which this key is
912          * authorized to be used after the user is successfully authenticated. This has effect if
913          * the key requires user authentication for its use (see
914          * {@link #setUserAuthenticationRequired(boolean)}).
915          *
916          * <p>By default, if user authentication is required, it must take place for every use of
917          * the key.
918          *
919          * <p>These cryptographic operations will throw {@link UserNotAuthenticatedException} during
920          * initialization if the user needs to be authenticated to proceed. This situation can be
921          * resolved by the user authenticating with the appropriate biometric or credential as
922          * required by the key. See {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)}
923          * and {@link BiometricManager.Authenticators}.
924          *
925          * <p>Once resolved, initializing a new cryptographic operation using this key (or any other
926          * key which is authorized to be used for a fixed duration of time after user
927          * authentication) should succeed provided the user authentication flow completed
928          * successfully.
929          *
930          * @param timeout duration in seconds or {@code 0} if user authentication must take place
931          *        for every use of the key.
932          * @param type set of authentication types which can authorize use of the key. See
933          *        {@link KeyProperties}.{@code AUTH} flags.
934          *
935          * @see #setUserAuthenticationRequired(boolean)
936          * @see BiometricPrompt
937          * @see BiometricPrompt.CryptoObject
938          * @see KeyguardManager
939          */
940         @NonNull
setUserAuthenticationParameters(@ntRangefrom = 0) int timeout, @KeyProperties.AuthEnum int type)941         public Builder setUserAuthenticationParameters(@IntRange(from = 0) int timeout,
942                                                        @KeyProperties.AuthEnum int type) {
943             if (timeout < 0) {
944                 throw new IllegalArgumentException("timeout must be 0 or larger");
945             }
946             mUserAuthenticationValidityDurationSeconds = timeout;
947             mUserAuthenticationType = type;
948             return this;
949         }
950 
951         /**
952          * Sets whether a test of user presence is required to be performed between the
953          * {@code Signature.initSign()} and {@code Signature.sign()} method calls. It requires that
954          * the KeyStore implementation have a direct way to validate the user presence for example
955          * a KeyStore hardware backed strongbox can use a button press that is observable in
956          * hardware. A test for user presence is tangential to authentication. The test can be part
957          * of an authentication step as long as this step can be validated by the hardware
958          * protecting the key and cannot be spoofed. For example, a physical button press can be
959          * used as a test of user presence if the other pins connected to the button are not able
960          * to simulate a button press. There must be no way for the primary processor to fake a
961          * button press, or that button must not be used as a test of user presence.
962          */
963         @NonNull
setUserPresenceRequired(boolean required)964         public Builder setUserPresenceRequired(boolean required) {
965             mUserPresenceRequired = required;
966             return this;
967         }
968 
969         /**
970          * Sets whether the key will remain authorized only until the device is removed from the
971          * user's body up to the limit of the authentication validity period (see
972          * {@link #setUserAuthenticationValidityDurationSeconds} and
973          * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
974          * user's body, the key will be considered unauthorized and the user will need to
975          * re-authenticate to use it. For keys without an authentication validity period this
976          * parameter has no effect.
977          *
978          * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
979          * effect; the device will always be considered to be "on-body" and the key will therefore
980          * remain authorized until the validity period ends.
981          *
982          * @param remainsValid if {@code true}, and if the device supports on-body detection, key
983          * will be invalidated when the device is removed from the user's body or when the
984          * authentication validity expires, whichever occurs first.
985          */
986         @NonNull
setUserAuthenticationValidWhileOnBody(boolean remainsValid)987         public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
988             mUserAuthenticationValidWhileOnBody = remainsValid;
989             return this;
990         }
991 
992         /**
993          * Sets whether this key should be invalidated on biometric enrollment.  This
994          * applies only to keys which require user authentication (see {@link
995          * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
996          * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
997          * valid for biometric authentication only.
998          *
999          * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
1000          * biometric authentication only are <em>irreversibly invalidated</em> when a new
1001          * biometric is enrolled, or when all existing biometrics are deleted.  That may be
1002          * changed by calling this method with {@code invalidateKey} set to {@code false}.
1003          *
1004          * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
1005          * improves security by ensuring that an unauthorized person who obtains the password can't
1006          * gain the use of biometric-authenticated keys by enrolling their own biometric.  However,
1007          * invalidating keys makes key-dependent operations impossible, requiring some fallback
1008          * procedure to authenticate the user and set up a new key.
1009          */
1010         @NonNull
setInvalidatedByBiometricEnrollment(boolean invalidateKey)1011         public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
1012             mInvalidatedByBiometricEnrollment = invalidateKey;
1013             return this;
1014         }
1015 
1016         /**
1017          * Set the secure user id that this key should be bound to.
1018          *
1019          * Normally an authentication-bound key is tied to the secure user id of the current user
1020          * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the
1021          * authenticator id of the current biometric set for keys requiring explicit biometric
1022          * authorization). If this parameter is set (this method returning non-zero value), the key
1023          * should be tied to the specified secure user id, overriding the logic above.
1024          *
1025          * This is only applicable when {@link #setUserAuthenticationRequired} is set to
1026          * {@code true}
1027          *
1028          * @see KeyProtection#getBoundToSpecificSecureUserId()
1029          * @hide
1030          */
1031         @TestApi
setBoundToSpecificSecureUserId(long secureUserId)1032         public Builder setBoundToSpecificSecureUserId(long secureUserId) {
1033             mBoundToSecureUserId = secureUserId;
1034             return this;
1035         }
1036 
1037         /**
1038          * Set whether this key is critical to the device encryption flow
1039          *
1040          * This is a special flag only available to system servers to indicate the current key
1041          * is part of the device encryption flow.
1042          *
1043          * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
1044          * @hide
1045          */
setCriticalToDeviceEncryption(boolean critical)1046         public Builder setCriticalToDeviceEncryption(boolean critical) {
1047             mCriticalToDeviceEncryption = critical;
1048             return this;
1049         }
1050 
1051         /**
1052          * Sets whether the keystore requires the screen to be unlocked before allowing decryption
1053          * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
1054          * key while the screen is locked will fail. A locked device requires a PIN, password,
1055          * biometric, or other trusted factor to access. While the screen is locked, the key can
1056          * still be used for encryption or signature verification.
1057          */
1058         @NonNull
setUnlockedDeviceRequired(boolean unlockedDeviceRequired)1059         public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
1060             mUnlockedDeviceRequired = unlockedDeviceRequired;
1061             return this;
1062         }
1063 
1064         /**
1065          * Sets whether this key should be protected by a StrongBox security chip.
1066          */
1067         @NonNull
setIsStrongBoxBacked(boolean isStrongBoxBacked)1068         public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
1069             mIsStrongBoxBacked = isStrongBoxBacked;
1070             return this;
1071         }
1072 
1073         /**
1074          * Sets the maximum number of times the key is allowed to be used. After every use of the
1075          * key, the use counter will decrease. This authorization applies only to secret key and
1076          * private key operations. Public key operations are not restricted. For example, after
1077          * successfully encrypting and decrypting data using methods such as
1078          * {@link Cipher#doFinal()}, the use counter of the secret key will decrease. After
1079          * successfully signing data using methods such as {@link Signature#sign()}, the use
1080          * counter of the private key will decrease.
1081          *
1082          * When the use counter is depleted, the key will be marked for deletion by Android
1083          * Keystore and any subsequent attempt to use the key will throw
1084          * {@link KeyPermanentlyInvalidatedException}. There is no key to be loaded from the
1085          * Android Keystore once the exhausted key is permanently deleted, as if the key never
1086          * existed before.
1087          *
1088          * <p>By default, there is no restriction on the usage of key.
1089          *
1090          * <p>Some secure hardware may not support this feature at all, in which case it will
1091          * be enforced in software, some secure hardware may support it but only with
1092          * maxUsageCount = 1, and some secure hardware may support it with larger value
1093          * of maxUsageCount.
1094          *
1095          * <p>The PackageManger feature flags:
1096          * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_SINGLE_USE_KEY} and
1097          * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_LIMITED_USE_KEY} can be used
1098          * to check whether the secure hardware cannot enforce this feature, can only enforce it
1099          * with maxUsageCount = 1, or can enforce it with larger value of maxUsageCount.
1100          *
1101          * @param maxUsageCount maximum number of times the key is allowed to be used or
1102          *        {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there is no restriction on the
1103          *        usage.
1104          */
1105         @NonNull
setMaxUsageCount(int maxUsageCount)1106         public Builder setMaxUsageCount(int maxUsageCount) {
1107             if (maxUsageCount == KeyProperties.UNRESTRICTED_USAGE_COUNT || maxUsageCount > 0) {
1108                 mMaxUsageCount = maxUsageCount;
1109                 return this;
1110             }
1111             throw new IllegalArgumentException("maxUsageCount is not valid");
1112         }
1113 
1114         /**
1115          * Sets whether the key should be rollback-resistant, meaning that when deleted it is
1116          * guaranteed to be permanently deleted and unusable.  Not all implementations support
1117          * rollback-resistant keys.  This method is hidden because implementations only support a
1118          * limited number of rollback-resistant keys; currently the available space is reserved for
1119          * critical system keys.
1120          *
1121          * @hide
1122          */
1123         @NonNull
setRollbackResistant(boolean rollbackResistant)1124         public Builder setRollbackResistant(boolean rollbackResistant) {
1125             mRollbackResistant = rollbackResistant;
1126             return this;
1127         }
1128 
1129         /**
1130          * Builds an instance of {@link KeyProtection}.
1131          *
1132          * @throws IllegalArgumentException if a required field is missing
1133          */
1134         @NonNull
build()1135         public KeyProtection build() {
1136             return new KeyProtection(
1137                     mKeyValidityStart,
1138                     mKeyValidityForOriginationEnd,
1139                     mKeyValidityForConsumptionEnd,
1140                     mPurposes,
1141                     mEncryptionPaddings,
1142                     mSignaturePaddings,
1143                     mDigests,
1144                     mBlockModes,
1145                     mRandomizedEncryptionRequired,
1146                     mUserAuthenticationRequired,
1147                     mUserAuthenticationType,
1148                     mUserAuthenticationValidityDurationSeconds,
1149                     mUserPresenceRequired,
1150                     mUserAuthenticationValidWhileOnBody,
1151                     mInvalidatedByBiometricEnrollment,
1152                     mBoundToSecureUserId,
1153                     mCriticalToDeviceEncryption,
1154                     mUserConfirmationRequired,
1155                     mUnlockedDeviceRequired,
1156                     mIsStrongBoxBacked,
1157                     mMaxUsageCount,
1158                     mRollbackResistant);
1159         }
1160     }
1161 }
1162