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