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 int mUserAuthenticationValidityDurationSeconds;
229     private final boolean mUserPresenceRequred;
230     private final boolean mUserAuthenticationValidWhileOnBody;
231     private final boolean mInvalidatedByBiometricEnrollment;
232     private final long mBoundToSecureUserId;
233     private final boolean mCriticalToDeviceEncryption;
234     private final boolean mUserConfirmationRequired;
235     private final boolean mUnlockedDeviceRequired;
236     private final boolean mIsStrongBoxBacked;
237 
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, int userAuthenticationValidityDurationSeconds, boolean userPresenceRequred, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment, long boundToSecureUserId, boolean criticalToDeviceEncryption, boolean userConfirmationRequired, boolean unlockedDeviceRequired, boolean isStrongBoxBacked)238     private KeyProtection(
239             Date keyValidityStart,
240             Date keyValidityForOriginationEnd,
241             Date keyValidityForConsumptionEnd,
242             @KeyProperties.PurposeEnum int purposes,
243             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
244             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
245             @KeyProperties.DigestEnum String[] digests,
246             @KeyProperties.BlockModeEnum String[] blockModes,
247             boolean randomizedEncryptionRequired,
248             boolean userAuthenticationRequired,
249             int userAuthenticationValidityDurationSeconds,
250             boolean userPresenceRequred,
251             boolean userAuthenticationValidWhileOnBody,
252             boolean invalidatedByBiometricEnrollment,
253             long boundToSecureUserId,
254             boolean criticalToDeviceEncryption,
255             boolean userConfirmationRequired,
256             boolean unlockedDeviceRequired,
257             boolean isStrongBoxBacked) {
258         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
259         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
260         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
261         mPurposes = purposes;
262         mEncryptionPaddings =
263                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
264         mSignaturePaddings =
265                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
266         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
267         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
268         mRandomizedEncryptionRequired = randomizedEncryptionRequired;
269         mUserAuthenticationRequired = userAuthenticationRequired;
270         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
271         mUserPresenceRequred = userPresenceRequred;
272         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
273         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
274         mBoundToSecureUserId = boundToSecureUserId;
275         mCriticalToDeviceEncryption = criticalToDeviceEncryption;
276         mUserConfirmationRequired = userConfirmationRequired;
277         mUnlockedDeviceRequired = unlockedDeviceRequired;
278         mIsStrongBoxBacked = isStrongBoxBacked;
279     }
280 
281     /**
282      * Gets the time instant before which the key is not yet valid.
283      *
284      * @return instant or {@code null} if not restricted.
285      */
286     @Nullable
getKeyValidityStart()287     public Date getKeyValidityStart() {
288         return Utils.cloneIfNotNull(mKeyValidityStart);
289     }
290 
291     /**
292      * Gets the time instant after which the key is no long valid for decryption and verification.
293      *
294      * @return instant or {@code null} if not restricted.
295      */
296     @Nullable
getKeyValidityForConsumptionEnd()297     public Date getKeyValidityForConsumptionEnd() {
298         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
299     }
300 
301     /**
302      * Gets the time instant after which the key is no long valid for encryption and signing.
303      *
304      * @return instant or {@code null} if not restricted.
305      */
306     @Nullable
getKeyValidityForOriginationEnd()307     public Date getKeyValidityForOriginationEnd() {
308         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
309     }
310 
311     /**
312      * Gets the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
313      * Attempts to use the key for any other purpose will be rejected.
314      *
315      * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
316      */
getPurposes()317     public @KeyProperties.PurposeEnum int getPurposes() {
318         return mPurposes;
319     }
320 
321     /**
322      * Gets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code PKCS1Padding},
323      * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to use
324      * the key with any other padding scheme will be rejected.
325      *
326      * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
327      */
328     @NonNull
getEncryptionPaddings()329     public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
330         return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
331     }
332 
333     /**
334      * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
335      * can be used when signing/verifying. Attempts to use the key with any other padding scheme
336      * will be rejected.
337      *
338      * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
339      */
340     @NonNull
getSignaturePaddings()341     public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
342         return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
343     }
344 
345     /**
346      * Gets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the key
347      * can be used.
348      *
349      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
350      *
351      * @throws IllegalStateException if this set has not been specified.
352      *
353      * @see #isDigestsSpecified()
354      */
355     @NonNull
getDigests()356     public @KeyProperties.DigestEnum String[] getDigests() {
357         if (mDigests == null) {
358             throw new IllegalStateException("Digests not specified");
359         }
360         return ArrayUtils.cloneIfNotEmpty(mDigests);
361     }
362 
363     /**
364      * Returns {@code true} if the set of digest algorithms with which the key can be used has been
365      * specified.
366      *
367      * @see #getDigests()
368      */
isDigestsSpecified()369     public boolean isDigestsSpecified() {
370         return mDigests != null;
371     }
372 
373     /**
374      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
375      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
376      * rejected.
377      *
378      * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
379      */
380     @NonNull
getBlockModes()381     public @KeyProperties.BlockModeEnum String[] getBlockModes() {
382         return ArrayUtils.cloneIfNotEmpty(mBlockModes);
383     }
384 
385     /**
386      * Returns {@code true} if encryption using this key must be sufficiently randomized to produce
387      * different ciphertexts for the same plaintext every time. The formal cryptographic property
388      * being required is <em>indistinguishability under chosen-plaintext attack ({@code
389      * IND-CPA})</em>. This property is important because it mitigates several classes of
390      * weaknesses due to which ciphertext may leak information about plaintext. For example, if a
391      * given plaintext always produces the same ciphertext, an attacker may see the repeated
392      * ciphertexts and be able to deduce something about the plaintext.
393      */
isRandomizedEncryptionRequired()394     public boolean isRandomizedEncryptionRequired() {
395         return mRandomizedEncryptionRequired;
396     }
397 
398     /**
399      * Returns {@code true} if the key is authorized to be used only if the user has been
400      * authenticated.
401      *
402      * <p>This authorization applies only to secret key and private key operations. Public key
403      * operations are not restricted.
404      *
405      * @see #getUserAuthenticationValidityDurationSeconds()
406      * @see Builder#setUserAuthenticationRequired(boolean)
407      */
isUserAuthenticationRequired()408     public boolean isUserAuthenticationRequired() {
409         return mUserAuthenticationRequired;
410     }
411 
412     /**
413      * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
414      * user.
415      *
416      * Confirmation is separate from user authentication (see
417      * {@link #isUserAuthenticationRequired()}). Keys can be created that require confirmation but
418      * not user authentication, or user authentication but not confirmation, or both. Confirmation
419      * verifies that some user with physical possession of the device has approved a displayed
420      * message. User authentication verifies that the correct user is present and has
421      * authenticated.
422      *
423      * <p>This authorization applies only to secret key and private key operations. Public key
424      * operations are not restricted.
425      *
426      * @see Builder#setUserConfirmationRequired(boolean)
427      */
isUserConfirmationRequired()428     public boolean isUserConfirmationRequired() {
429         return mUserConfirmationRequired;
430     }
431 
432     /**
433      * Gets the duration of time (seconds) for which this key is authorized to be used after the
434      * user is successfully authenticated. This has effect only if user authentication is required
435      * (see {@link #isUserAuthenticationRequired()}).
436      *
437      * <p>This authorization applies only to secret key and private key operations. Public key
438      * operations are not restricted.
439      *
440      * @return duration in seconds or {@code -1} if authentication is required for every use of the
441      *         key.
442      *
443      * @see #isUserAuthenticationRequired()
444      * @see Builder#setUserAuthenticationValidityDurationSeconds(int)
445      */
getUserAuthenticationValidityDurationSeconds()446     public int getUserAuthenticationValidityDurationSeconds() {
447         return mUserAuthenticationValidityDurationSeconds;
448     }
449 
450     /**
451      * Returns {@code true} if the key is authorized to be used only if a test of user presence has
452      * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls.
453      * It requires that the KeyStore implementation have a direct way to validate the user presence
454      * for example a KeyStore hardware backed strongbox can use a button press that is observable
455      * in hardware. A test for user presence is tangential to authentication. The test can be part
456      * of an authentication step as long as this step can be validated by the hardware protecting
457      * the key and cannot be spoofed. For example, a physical button press can be used as a test of
458      * user presence if the other pins connected to the button are not able to simulate a button
459      * press. There must be no way for the primary processor to fake a button press, or that
460      * button must not be used as a test of user presence.
461      */
isUserPresenceRequired()462     public boolean isUserPresenceRequired() {
463         return mUserPresenceRequred;
464     }
465 
466     /**
467      * Returns {@code true} if the key will be de-authorized when the device is removed from the
468      * user's body.  This option has no effect on keys that don't have an authentication validity
469      * duration, and has no effect if the device lacks an on-body sensor.
470      *
471      * <p>Authorization applies only to secret key and private key operations. Public key operations
472      * are not restricted.
473      *
474      * @see #isUserAuthenticationRequired()
475      * @see #getUserAuthenticationValidityDurationSeconds()
476      * @see Builder#setUserAuthenticationValidWhileOnBody(boolean)
477      */
isUserAuthenticationValidWhileOnBody()478     public boolean isUserAuthenticationValidWhileOnBody() {
479         return mUserAuthenticationValidWhileOnBody;
480     }
481 
482     /**
483      * Returns {@code true} if the key is irreversibly invalidated when a new biometric is
484      * enrolled or all enrolled biometrics are removed. This has effect only for keys that
485      * require biometric user authentication for every use.
486      *
487      * @see #isUserAuthenticationRequired()
488      * @see #getUserAuthenticationValidityDurationSeconds()
489      * @see Builder#setInvalidatedByBiometricEnrollment(boolean)
490      */
isInvalidatedByBiometricEnrollment()491     public boolean isInvalidatedByBiometricEnrollment() {
492         return mInvalidatedByBiometricEnrollment;
493     }
494 
495     /**
496      * Return the secure user id that this key should be bound to.
497      *
498      * Normally an authentication-bound key is tied to the secure user id of the current user
499      * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the authenticator
500      * id of the current biometric set for keys requiring explicit biometric authorization).
501      * If this parameter is set (this method returning non-zero value), the key should be tied to
502      * the specified secure user id, overriding the logic above.
503      *
504      * This is only applicable when {@link #isUserAuthenticationRequired} is {@code true}
505      *
506      * @see KeymasterUtils#addUserAuthArgs
507      * @hide
508      */
509     @TestApi
getBoundToSpecificSecureUserId()510     public long getBoundToSpecificSecureUserId() {
511         return mBoundToSecureUserId;
512     }
513 
514     /**
515      * Return whether this key is critical to the device encryption flow.
516      *
517      * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
518      * @hide
519      */
isCriticalToDeviceEncryption()520     public boolean isCriticalToDeviceEncryption() {
521         return mCriticalToDeviceEncryption;
522     }
523 
524     /**
525      * Returns {@code true} if the screen must be unlocked for this key to be used for decryption or
526      * signing. Encryption and signature verification will still be available when the screen is
527      * locked.
528      *
529      * @see Builder#setUnlockedDeviceRequired(boolean)
530      */
isUnlockedDeviceRequired()531     public boolean isUnlockedDeviceRequired() {
532         return mUnlockedDeviceRequired;
533     }
534 
535     /**
536      * Returns {@code true} if the key is protected by a Strongbox security chip.
537      * @hide
538      */
isStrongBoxBacked()539     public boolean isStrongBoxBacked() {
540         return mIsStrongBoxBacked;
541     }
542 
543     /**
544      * Builder of {@link KeyProtection} instances.
545      */
546     public final static class Builder {
547         private @KeyProperties.PurposeEnum int mPurposes;
548 
549         private Date mKeyValidityStart;
550         private Date mKeyValidityForOriginationEnd;
551         private Date mKeyValidityForConsumptionEnd;
552         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
553         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
554         private @KeyProperties.DigestEnum String[] mDigests;
555         private @KeyProperties.BlockModeEnum String[] mBlockModes;
556         private boolean mRandomizedEncryptionRequired = true;
557         private boolean mUserAuthenticationRequired;
558         private int mUserAuthenticationValidityDurationSeconds = -1;
559         private boolean mUserPresenceRequired = false;
560         private boolean mUserAuthenticationValidWhileOnBody;
561         private boolean mInvalidatedByBiometricEnrollment = true;
562         private boolean mUserConfirmationRequired;
563         private boolean mUnlockedDeviceRequired = false;
564 
565         private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID;
566         private boolean mCriticalToDeviceEncryption = false;
567         private boolean mIsStrongBoxBacked = false;
568 
569         /**
570          * Creates a new instance of the {@code Builder}.
571          *
572          * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be
573          *        used. Attempts to use the key for any other purpose will be rejected.
574          *
575          *        <p>See {@link KeyProperties}.{@code PURPOSE} flags.
576          */
Builder(@eyProperties.PurposeEnum int purposes)577         public Builder(@KeyProperties.PurposeEnum int purposes) {
578             mPurposes = purposes;
579         }
580 
581         /**
582          * Sets the time instant before which the key is not yet valid.
583          *
584          * <p>By default, the key is valid at any instant.
585          *
586          * @see #setKeyValidityEnd(Date)
587          */
588         @NonNull
setKeyValidityStart(Date startDate)589         public Builder setKeyValidityStart(Date startDate) {
590             mKeyValidityStart = Utils.cloneIfNotNull(startDate);
591             return this;
592         }
593 
594         /**
595          * Sets the time instant after which the key is no longer valid.
596          *
597          * <p>By default, the key is valid at any instant.
598          *
599          * @see #setKeyValidityStart(Date)
600          * @see #setKeyValidityForConsumptionEnd(Date)
601          * @see #setKeyValidityForOriginationEnd(Date)
602          */
603         @NonNull
setKeyValidityEnd(Date endDate)604         public Builder setKeyValidityEnd(Date endDate) {
605             setKeyValidityForOriginationEnd(endDate);
606             setKeyValidityForConsumptionEnd(endDate);
607             return this;
608         }
609 
610         /**
611          * Sets the time instant after which the key is no longer valid for encryption and signing.
612          *
613          * <p>By default, the key is valid at any instant.
614          *
615          * @see #setKeyValidityForConsumptionEnd(Date)
616          */
617         @NonNull
setKeyValidityForOriginationEnd(Date endDate)618         public Builder setKeyValidityForOriginationEnd(Date endDate) {
619             mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate);
620             return this;
621         }
622 
623         /**
624          * Sets the time instant after which the key is no longer valid for decryption and
625          * verification.
626          *
627          * <p>By default, the key is valid at any instant.
628          *
629          * @see #setKeyValidityForOriginationEnd(Date)
630          */
631         @NonNull
setKeyValidityForConsumptionEnd(Date endDate)632         public Builder setKeyValidityForConsumptionEnd(Date endDate) {
633             mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate);
634             return this;
635         }
636 
637         /**
638          * Sets the set of padding schemes (e.g., {@code OAEPPadding}, {@code PKCS7Padding},
639          * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to
640          * use the key with any other padding scheme will be rejected.
641          *
642          * <p>This must be specified for keys which are used for encryption/decryption.
643          *
644          * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it
645          * is usually necessary to authorize the use of no/any padding
646          * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding
647          * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is
648          * required by some cipher suites, and some stacks request decryption using no padding
649          * whereas others request PKCS#1 padding.
650          *
651          * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
652          */
653         @NonNull
setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)654         public Builder setEncryptionPaddings(
655                 @KeyProperties.EncryptionPaddingEnum String... paddings) {
656             mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings);
657             return this;
658         }
659 
660         /**
661          * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
662          * can be used when signing/verifying. Attempts to use the key with any other padding scheme
663          * will be rejected.
664          *
665          * <p>This must be specified for RSA keys which are used for signing/verification.
666          *
667          * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
668          */
669         @NonNull
setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)670         public Builder setSignaturePaddings(
671                 @KeyProperties.SignaturePaddingEnum String... paddings) {
672             mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings);
673             return this;
674         }
675 
676         /**
677          * Sets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the
678          * key can be used. Attempts to use the key with any other digest algorithm will be
679          * rejected.
680          *
681          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
682          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
683          * HMAC keys, the default is the digest specified in {@link Key#getAlgorithm()} (e.g.,
684          * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
685          * for more than one digest.
686          *
687          * <p>For private keys used for TLS/SSL client or server authentication it is usually
688          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
689          * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use
690          * a private key to sign it.
691          *
692          * <p>See {@link KeyProperties}.{@code DIGEST} constants.
693          */
694         @NonNull
setDigests(@eyProperties.DigestEnum String... digests)695         public Builder setDigests(@KeyProperties.DigestEnum String... digests) {
696             mDigests = ArrayUtils.cloneIfNotEmpty(digests);
697             return this;
698         }
699 
700         /**
701          * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
702          * used when encrypting/decrypting. Attempts to use the key with any other block modes will
703          * be rejected.
704          *
705          * <p>This must be specified for symmetric encryption/decryption keys.
706          *
707          * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
708          */
709         @NonNull
setBlockModes(@eyProperties.BlockModeEnum String... blockModes)710         public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) {
711             mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes);
712             return this;
713         }
714 
715         /**
716          * Sets whether encryption using this key must be sufficiently randomized to produce
717          * different ciphertexts for the same plaintext every time. The formal cryptographic
718          * property being required is <em>indistinguishability under chosen-plaintext attack
719          * ({@code IND-CPA})</em>. This property is important because it mitigates several classes
720          * of weaknesses due to which ciphertext may leak information about plaintext. For example,
721          * if a given plaintext always produces the same ciphertext, an attacker may see the
722          * repeated ciphertexts and be able to deduce something about the plaintext.
723          *
724          * <p>By default, {@code IND-CPA} is required.
725          *
726          * <p>When {@code IND-CPA} is required:
727          * <ul>
728          * <li>transformation which do not offer {@code IND-CPA}, such as symmetric ciphers using
729          * {@code ECB} mode or RSA encryption without padding, are prohibited;</li>
730          * <li>in transformations which use an IV, such as symmetric ciphers in {@code GCM},
731          * {@code CBC}, and {@code CTR} block modes, caller-provided IVs are rejected when
732          * encrypting, to ensure that only random IVs are used.</li>
733          *
734          * <p>Before disabling this requirement, consider the following approaches instead:
735          * <ul>
736          * <li>If you are generating a random IV for encryption and then initializing a {@code}
737          * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV
738          * instead. This will occur if the {@code Cipher} is initialized for encryption without an
739          * IV. The IV can then be queried via {@link Cipher#getIV()}.</li>
740          * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully
741          * random, such as the name of the file being encrypted, or transaction ID, or password,
742          * or a device identifier), consider changing your design to use a random IV which will then
743          * be provided in addition to the ciphertext to the entities which need to decrypt the
744          * ciphertext.</li>
745          * <li>If you are using RSA encryption without padding, consider switching to padding
746          * schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li>
747          * </ul>
748          */
749         @NonNull
setRandomizedEncryptionRequired(boolean required)750         public Builder setRandomizedEncryptionRequired(boolean required) {
751             mRandomizedEncryptionRequired = required;
752             return this;
753         }
754 
755         /**
756          * Sets whether this key is authorized to be used only if the user has been authenticated.
757          *
758          * <p>By default, the key is authorized to be used regardless of whether the user has been
759          * authenticated.
760          *
761          * <p>When user authentication is required:
762          * <ul>
763          * <li>The key can only be import if secure lock screen is set up (see
764          * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user
765          * authentication takes place for every use of the key (see
766          * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric
767          * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li>
768          * <li>The use of the key must be authorized by the user by authenticating to this Android
769          * device using a subset of their secure lock screen credentials such as
770          * password/PIN/pattern or biometric.
771          * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More
772          * information</a>.
773          * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is
774          * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user)
775          * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator).
776          * Additionally, if the key requires that user authentication takes place for every use of
777          * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\
778          * no more biometrics are enrolled, unless {@link
779          * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after
780          * enrollment. Attempts to initialize cryptographic operations using such keys will throw
781          * {@link KeyPermanentlyInvalidatedException}.</li> </ul>
782          *
783          * <p>This authorization applies only to secret key and private key operations. Public key
784          * operations are not restricted.
785          *
786          * @see #setUserAuthenticationValidityDurationSeconds(int)
787          * @see KeyguardManager#isDeviceSecure()
788          * @see BiometricManager#canAuthenticate()
789          */
790         @NonNull
setUserAuthenticationRequired(boolean required)791         public Builder setUserAuthenticationRequired(boolean required) {
792             mUserAuthenticationRequired = required;
793             return this;
794         }
795 
796         /**
797          * Sets whether this key is authorized to be used only for messages confirmed by the
798          * user.
799          *
800          * Confirmation is separate from user authentication (see
801          * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require
802          * confirmation but not user authentication, or user authentication but not confirmation,
803          * or both. Confirmation verifies that some user with physical possession of the device has
804          * approved a displayed message. User authentication verifies that the correct user is
805          * present and has authenticated.
806          *
807          * <p>This authorization applies only to secret key and private key operations. Public key
808          * operations are not restricted.
809          *
810          * See {@link android.security.ConfirmationPrompt} class for
811          * more details about user confirmations.
812          */
813         @NonNull
setUserConfirmationRequired(boolean required)814         public Builder setUserConfirmationRequired(boolean required) {
815             mUserConfirmationRequired = required;
816             return this;
817         }
818 
819         /**
820          * Sets the duration of time (seconds) for which this key is authorized to be used after the
821          * user is successfully authenticated. This has effect if the key requires user
822          * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}).
823          *
824          * <p>By default, if user authentication is required, it must take place for every use of
825          * the key.
826          *
827          * <p>Cryptographic operations involving keys which require user authentication to take
828          * place for every operation can only use biometric authentication. This is achieved by
829          * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac})
830          * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking
831          * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with
832          * the cryptographic operation only if the authentication flow succeeds.
833          *
834          * <p>Cryptographic operations involving keys which are authorized to be used for a duration
835          * of time after a successful user authentication event can only use secure lock screen
836          * authentication. These cryptographic operations will throw
837          * {@link UserNotAuthenticatedException} during initialization if the user needs to be
838          * authenticated to proceed. This situation can be resolved by the user unlocking the secure
839          * lock screen of the Android or by going through the confirm credential flow initiated by
840          * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}.
841          * Once resolved, initializing a new cryptographic operation using this key (or any other
842          * key which is authorized to be used for a fixed duration of time after user
843          * authentication) should succeed provided the user authentication flow completed
844          * successfully.
845          *
846          * @param seconds duration in seconds or {@code -1} if user authentication must take place
847          *        for every use of the key.
848          *
849          * @see #setUserAuthenticationRequired(boolean)
850          * @see BiometricPrompt
851          * @see BiometricPrompt.CryptoObject
852          * @see KeyguardManager
853          */
854         @NonNull
setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)855         public Builder setUserAuthenticationValidityDurationSeconds(
856                 @IntRange(from = -1) int seconds) {
857             if (seconds < -1) {
858                 throw new IllegalArgumentException("seconds must be -1 or larger");
859             }
860             mUserAuthenticationValidityDurationSeconds = seconds;
861             return this;
862         }
863 
864         /**
865          * Sets whether a test of user presence is required to be performed between the
866          * {@code Signature.initSign()} and {@code Signature.sign()} method calls. It requires that
867          * the KeyStore implementation have a direct way to validate the user presence for example
868          * a KeyStore hardware backed strongbox can use a button press that is observable in
869          * hardware. A test for user presence is tangential to authentication. The test can be part
870          * of an authentication step as long as this step can be validated by the hardware
871          * protecting the key and cannot be spoofed. For example, a physical button press can be
872          * used as a test of user presence if the other pins connected to the button are not able
873          * to simulate a button press. There must be no way for the primary processor to fake a
874          * button press, or that button must not be used as a test of user presence.
875          */
876         @NonNull
setUserPresenceRequired(boolean required)877         public Builder setUserPresenceRequired(boolean required) {
878             mUserPresenceRequired = required;
879             return this;
880         }
881 
882         /**
883          * Sets whether the key will remain authorized only until the device is removed from the
884          * user's body up to the limit of the authentication validity period (see
885          * {@link #setUserAuthenticationValidityDurationSeconds} and
886          * {@link #setUserAuthenticationRequired}). Once the device has been removed from the
887          * user's body, the key will be considered unauthorized and the user will need to
888          * re-authenticate to use it. For keys without an authentication validity period this
889          * parameter has no effect.
890          *
891          * <p>Similarly, on devices that do not have an on-body sensor, this parameter will have no
892          * effect; the device will always be considered to be "on-body" and the key will therefore
893          * remain authorized until the validity period ends.
894          *
895          * @param remainsValid if {@code true}, and if the device supports on-body detection, key
896          * will be invalidated when the device is removed from the user's body or when the
897          * authentication validity expires, whichever occurs first.
898          */
899         @NonNull
setUserAuthenticationValidWhileOnBody(boolean remainsValid)900         public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) {
901             mUserAuthenticationValidWhileOnBody = remainsValid;
902             return this;
903         }
904 
905         /**
906          * Sets whether this key should be invalidated on biometric enrollment.  This
907          * applies only to keys which require user authentication (see {@link
908          * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been
909          * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is
910          * valid for biometric authentication only.
911          *
912          * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for
913          * biometric authentication only are <em>irreversibly invalidated</em> when a new
914          * biometric is enrolled, or when all existing biometrics are deleted.  That may be
915          * changed by calling this method with {@code invalidateKey} set to {@code false}.
916          *
917          * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics
918          * improves security by ensuring that an unauthorized person who obtains the password can't
919          * gain the use of biometric-authenticated keys by enrolling their own biometric.  However,
920          * invalidating keys makes key-dependent operations impossible, requiring some fallback
921          * procedure to authenticate the user and set up a new key.
922          */
923         @NonNull
setInvalidatedByBiometricEnrollment(boolean invalidateKey)924         public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) {
925             mInvalidatedByBiometricEnrollment = invalidateKey;
926             return this;
927         }
928 
929         /**
930          * Set the secure user id that this key should be bound to.
931          *
932          * Normally an authentication-bound key is tied to the secure user id of the current user
933          * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the
934          * authenticator id of the current biometric set for keys requiring explicit biometric
935          * authorization). If this parameter is set (this method returning non-zero value), the key
936          * should be tied to the specified secure user id, overriding the logic above.
937          *
938          * This is only applicable when {@link #setUserAuthenticationRequired} is set to
939          * {@code true}
940          *
941          * @see KeyProtection#getBoundToSpecificSecureUserId()
942          * @hide
943          */
944         @TestApi
setBoundToSpecificSecureUserId(long secureUserId)945         public Builder setBoundToSpecificSecureUserId(long secureUserId) {
946             mBoundToSecureUserId = secureUserId;
947             return this;
948         }
949 
950         /**
951          * Set whether this key is critical to the device encryption flow
952          *
953          * This is a special flag only available to system servers to indicate the current key
954          * is part of the device encryption flow.
955          *
956          * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
957          * @hide
958          */
setCriticalToDeviceEncryption(boolean critical)959         public Builder setCriticalToDeviceEncryption(boolean critical) {
960             mCriticalToDeviceEncryption = critical;
961             return this;
962         }
963 
964         /**
965          * Sets whether the keystore requires the screen to be unlocked before allowing decryption
966          * using this key. If this is set to {@code true}, any attempt to decrypt or sign using this
967          * key while the screen is locked will fail. A locked device requires a PIN, password,
968          * biometric, or other trusted factor to access. While the screen is locked, the key can
969          * still be used for encryption or signature verification.
970          */
971         @NonNull
setUnlockedDeviceRequired(boolean unlockedDeviceRequired)972         public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) {
973             mUnlockedDeviceRequired = unlockedDeviceRequired;
974             return this;
975         }
976 
977         /**
978          * Sets whether this key should be protected by a StrongBox security chip.
979          * @hide
980          */
981         @NonNull
setIsStrongBoxBacked(boolean isStrongBoxBacked)982         public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) {
983             mIsStrongBoxBacked = isStrongBoxBacked;
984             return this;
985         }
986 
987         /**
988          * Builds an instance of {@link KeyProtection}.
989          *
990          * @throws IllegalArgumentException if a required field is missing
991          */
992         @NonNull
build()993         public KeyProtection build() {
994             return new KeyProtection(
995                     mKeyValidityStart,
996                     mKeyValidityForOriginationEnd,
997                     mKeyValidityForConsumptionEnd,
998                     mPurposes,
999                     mEncryptionPaddings,
1000                     mSignaturePaddings,
1001                     mDigests,
1002                     mBlockModes,
1003                     mRandomizedEncryptionRequired,
1004                     mUserAuthenticationRequired,
1005                     mUserAuthenticationValidityDurationSeconds,
1006                     mUserPresenceRequired,
1007                     mUserAuthenticationValidWhileOnBody,
1008                     mInvalidatedByBiometricEnrollment,
1009                     mBoundToSecureUserId,
1010                     mCriticalToDeviceEncryption,
1011                     mUserConfirmationRequired,
1012                     mUnlockedDeviceRequired,
1013                     mIsStrongBoxBacked);
1014         }
1015     }
1016 }
1017