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