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