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