1 /* 2 * Copyright (C) 2012 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.SystemApi; 24 import android.annotation.TestApi; 25 import android.app.KeyguardManager; 26 import android.compat.annotation.UnsupportedAppUsage; 27 import android.hardware.biometrics.BiometricManager; 28 import android.hardware.biometrics.BiometricPrompt; 29 import android.os.Build; 30 import android.security.GateKeeper; 31 import android.text.TextUtils; 32 33 import java.math.BigInteger; 34 import java.security.KeyPairGenerator; 35 import java.security.Signature; 36 import java.security.cert.Certificate; 37 import java.security.spec.AlgorithmParameterSpec; 38 import java.util.Collections; 39 import java.util.Date; 40 import java.util.HashSet; 41 import java.util.Set; 42 43 import javax.crypto.Cipher; 44 import javax.crypto.KeyGenerator; 45 import javax.crypto.Mac; 46 import javax.security.auth.x500.X500Principal; 47 48 /** 49 * {@link AlgorithmParameterSpec} for initializing a {@link KeyPairGenerator} or a 50 * {@link KeyGenerator} of the <a href="{@docRoot}training/articles/keystore.html">Android Keystore 51 * system</a>. The spec determines authorized uses of the key, such as whether user authentication 52 * is required for using the key, what operations are authorized (e.g., signing, but not 53 * decryption), with what parameters (e.g., only with a particular padding scheme or digest), and 54 * the key's validity start and end dates. Key use authorizations expressed in the spec apply 55 * only to secret keys and private keys -- public keys can be used for any supported operations. 56 * 57 * <p>To generate an asymmetric key pair or a symmetric key, create an instance of this class using 58 * the {@link Builder}, initialize a {@code KeyPairGenerator} or a {@code KeyGenerator} of the 59 * desired key type (e.g., {@code EC} or {@code AES} -- see 60 * {@link KeyProperties}.{@code KEY_ALGORITHM} constants) from the {@code AndroidKeyStore} provider 61 * with the {@code KeyGenParameterSpec} instance, and then generate a key or key pair using 62 * {@link KeyGenerator#generateKey()} or {@link KeyPairGenerator#generateKeyPair()}. 63 * 64 * <p>The generated key pair or key will be returned by the generator and also stored in the Android 65 * Keystore under the alias specified in this spec. To obtain the secret or private key from the 66 * Android Keystore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)} 67 * or {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}. 68 * To obtain the public key from the Android Keystore use 69 * {@link java.security.KeyStore#getCertificate(String)} and then 70 * {@link Certificate#getPublicKey()}. 71 * 72 * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android 73 * Keystore, generated private keys implement {@link java.security.interfaces.ECKey} or 74 * {@link java.security.interfaces.RSAKey} interfaces whereas public keys implement 75 * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey} 76 * interfaces. 77 * 78 * <p>For asymmetric key pairs, a X.509 certificate will be also generated and stored in the Android 79 * Keystore. This is because the {@link java.security.KeyStore} abstraction does not support storing 80 * key pairs without a certificate. The subject, serial number, and validity dates of the 81 * certificate can be customized in this spec. The certificate may be replaced at a later time by a 82 * certificate signed by a Certificate Authority (CA). 83 * 84 * <p>NOTE: If attestation is not requested using {@link Builder#setAttestationChallenge(byte[])}, 85 * generated certificate may be self-signed. If a private key is not authorized to sign the 86 * certificate, then the certificate will be created with an invalid signature which will not 87 * verify. Such a certificate is still useful because it provides access to the public key. To 88 * generate a valid signature for the certificate the key needs to be authorized for all of the 89 * following: 90 * <ul> 91 * <li>{@link KeyProperties#PURPOSE_SIGN},</li> 92 * <li>operation without requiring the user to be authenticated (see 93 * {@link Builder#setUserAuthenticationRequired(boolean)}),</li> 94 * <li>signing/origination at this moment in time (see {@link Builder#setKeyValidityStart(Date)} 95 * and {@link Builder#setKeyValidityForOriginationEnd(Date)}),</li> 96 * <li>suitable digest,</li> 97 * <li>(RSA keys only) padding scheme {@link KeyProperties#SIGNATURE_PADDING_RSA_PKCS1}.</li> 98 * </ul> 99 * 100 * <p>NOTE: The key material of the generated symmetric and private keys is not accessible. The key 101 * material of the public keys is accessible. 102 * 103 * <p>Instances of this class are immutable. 104 * 105 * <p><h3>Known issues</h3> 106 * A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be 107 * enforced even for public keys. To work around this issue extract the public key material to use 108 * outside of Android Keystore. For example: 109 * <pre> {@code 110 * PublicKey unrestrictedPublicKey = 111 * KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic( 112 * new X509EncodedKeySpec(publicKey.getEncoded())); 113 * }</pre> 114 * 115 * <p><h3>Example: NIST P-256 EC key pair for signing/verification using ECDSA</h3> 116 * This example illustrates how to generate a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair 117 * in the Android KeyStore system under alias {@code key1} where the private key is authorized to be 118 * used only for signing using SHA-256, SHA-384, or SHA-512 digest and only if the user has been 119 * authenticated within the last five minutes. The use of the public key is unrestricted (See Known 120 * Issues). 121 * <pre> {@code 122 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( 123 * KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); 124 * keyPairGenerator.initialize( 125 * new KeyGenParameterSpec.Builder( 126 * "key1", 127 * KeyProperties.PURPOSE_SIGN) 128 * .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")) 129 * .setDigests(KeyProperties.DIGEST_SHA256, 130 * KeyProperties.DIGEST_SHA384, 131 * KeyProperties.DIGEST_SHA512) 132 * // Only permit the private key to be used if the user authenticated 133 * // within the last five minutes. 134 * .setUserAuthenticationRequired(true) 135 * .setUserAuthenticationValidityDurationSeconds(5 * 60) 136 * .build()); 137 * KeyPair keyPair = keyPairGenerator.generateKeyPair(); 138 * Signature signature = Signature.getInstance("SHA256withECDSA"); 139 * signature.initSign(keyPair.getPrivate()); 140 * ... 141 * 142 * // The key pair can also be obtained from the Android Keystore any time as follows: 143 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); 144 * keyStore.load(null); 145 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null); 146 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey(); 147 * }</pre> 148 * 149 * <p><h3>Example: RSA key pair for signing/verification using RSA-PSS</h3> 150 * This example illustrates how to generate an RSA key pair in the Android KeyStore system under 151 * alias {@code key1} authorized to be used only for signing using the RSA-PSS signature padding 152 * scheme with SHA-256 or SHA-512 digests. The use of the public key is unrestricted. 153 * <pre> {@code 154 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( 155 * KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); 156 * keyPairGenerator.initialize( 157 * new KeyGenParameterSpec.Builder( 158 * "key1", 159 * KeyProperties.PURPOSE_SIGN) 160 * .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) 161 * .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS) 162 * .build()); 163 * KeyPair keyPair = keyPairGenerator.generateKeyPair(); 164 * Signature signature = Signature.getInstance("SHA256withRSA/PSS"); 165 * signature.initSign(keyPair.getPrivate()); 166 * ... 167 * 168 * // The key pair can also be obtained from the Android Keystore any time as follows: 169 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); 170 * keyStore.load(null); 171 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null); 172 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey(); 173 * }</pre> 174 * 175 * <p><h3>Example: RSA key pair for encryption/decryption using RSA OAEP</h3> 176 * This example illustrates how to generate an RSA key pair in the Android KeyStore system under 177 * alias {@code key1} where the private key is authorized to be used only for decryption using RSA 178 * OAEP encryption padding scheme with SHA-256 or SHA-512 digests. The use of the public key is 179 * unrestricted. 180 * <pre> {@code 181 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( 182 * KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); 183 * keyPairGenerator.initialize( 184 * new KeyGenParameterSpec.Builder( 185 * "key1", 186 * KeyProperties.PURPOSE_DECRYPT) 187 * .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) 188 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) 189 * .build()); 190 * KeyPair keyPair = keyPairGenerator.generateKeyPair(); 191 * Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); 192 * cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); 193 * ... 194 * 195 * // The key pair can also be obtained from the Android Keystore any time as follows: 196 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); 197 * keyStore.load(null); 198 * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null); 199 * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey(); 200 * }</pre> 201 * 202 * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3> 203 * The following example illustrates how to generate an AES key in the Android KeyStore system under 204 * alias {@code key2} authorized to be used only for encryption/decryption in GCM mode with no 205 * padding. 206 * <pre> {@code 207 * KeyGenerator keyGenerator = KeyGenerator.getInstance( 208 * KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); 209 * keyGenerator.init( 210 * new KeyGenParameterSpec.Builder("key2", 211 * KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) 212 * .setBlockModes(KeyProperties.BLOCK_MODE_GCM) 213 * .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 214 * .build()); 215 * SecretKey key = keyGenerator.generateKey(); 216 * 217 * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 218 * cipher.init(Cipher.ENCRYPT_MODE, key); 219 * ... 220 * 221 * // The key can also be obtained from the Android Keystore any time as follows: 222 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); 223 * keyStore.load(null); 224 * key = (SecretKey) keyStore.getKey("key2", null); 225 * }</pre> 226 * 227 * <p><h3>Example: HMAC key for generating a MAC using SHA-256</h3> 228 * This example illustrates how to generate an HMAC key in the Android KeyStore system under alias 229 * {@code key2} authorized to be used only for generating an HMAC using SHA-256. 230 * <pre> {@code 231 * KeyGenerator keyGenerator = KeyGenerator.getInstance( 232 * KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore"); 233 * keyGenerator.init( 234 * new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build()); 235 * SecretKey key = keyGenerator.generateKey(); 236 * Mac mac = Mac.getInstance("HmacSHA256"); 237 * mac.init(key); 238 * ... 239 * 240 * // The key can also be obtained from the Android Keystore any time as follows: 241 * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); 242 * keyStore.load(null); 243 * key = (SecretKey) keyStore.getKey("key2", null); 244 * }</pre> 245 * 246 * <p><h3 id="example:ecdh">Example: EC key for ECDH key agreement</h3> 247 * This example illustrates how to generate an elliptic curve key pair, used to establish a shared 248 * secret with another party using ECDH key agreement. 249 * <pre> {@code 250 * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( 251 * KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); 252 * keyPairGenerator.initialize( 253 * new KeyGenParameterSpec.Builder( 254 * "eckeypair", 255 * KeyProperties.PURPOSE_AGREE_KEY) 256 * .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")) 257 * .build()); 258 * KeyPair myKeyPair = keyPairGenerator.generateKeyPair(); 259 * 260 * // Exchange public keys with server. A new ephemeral key MUST be used for every message. 261 * PublicKey serverEphemeralPublicKey; // Ephemeral key received from server. 262 * 263 * // Create a shared secret based on our private key and the other party's public key. 264 * KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "AndroidKeyStore"); 265 * keyAgreement.init(myKeyPair.getPrivate()); 266 * keyAgreement.doPhase(serverEphemeralPublicKey, true); 267 * byte[] sharedSecret = keyAgreement.generateSecret(); 268 * 269 * // sharedSecret cannot safely be used as a key yet. We must run it through a key derivation 270 * // function with some other data: "salt" and "info". Salt is an optional random value, 271 * // omitted in this example. It's good practice to include both public keys and any other 272 * // key negotiation data in info. Here we use the public keys and a label that indicates 273 * // messages encrypted with this key are coming from the server. 274 * byte[] salt = {}; 275 * ByteArrayOutputStream info = new ByteArrayOutputStream(); 276 * info.write("ECDH secp256r1 AES-256-GCM-SIV\0".getBytes(StandardCharsets.UTF_8)); 277 * info.write(myKeyPair.getPublic().getEncoded()); 278 * info.write(serverEphemeralPublicKey.getEncoded()); 279 * 280 * // This example uses the Tink library and the HKDF key derivation function. 281 * AesGcmSiv key = new AesGcmSiv(Hkdf.computeHkdf( 282 * "HMACSHA256", sharedSecret, salt, info.toByteArray(), 32)); 283 * byte[] associatedData = {}; 284 * return key.decrypt(ciphertext, associatedData); 285 * }</pre> 286 */ 287 public final class KeyGenParameterSpec implements AlgorithmParameterSpec, UserAuthArgs { 288 private static final X500Principal DEFAULT_ATTESTATION_CERT_SUBJECT = 289 new X500Principal("CN=Android Keystore Key"); 290 private static final X500Principal DEFAULT_SELF_SIGNED_CERT_SUBJECT = 291 new X500Principal("CN=Fake"); 292 private static final BigInteger DEFAULT_CERT_SERIAL_NUMBER = new BigInteger("1"); 293 private static final Date DEFAULT_CERT_NOT_BEFORE = new Date(0L); // Jan 1 1970 294 private static final Date DEFAULT_CERT_NOT_AFTER = new Date(2461449600000L); // Jan 1 2048 295 296 private final String mKeystoreAlias; 297 private final @KeyProperties.Namespace int mNamespace; 298 private final int mKeySize; 299 private final AlgorithmParameterSpec mSpec; 300 private final X500Principal mCertificateSubject; 301 private final BigInteger mCertificateSerialNumber; 302 private final Date mCertificateNotBefore; 303 private final Date mCertificateNotAfter; 304 private final Date mKeyValidityStart; 305 private final Date mKeyValidityForOriginationEnd; 306 private final Date mKeyValidityForConsumptionEnd; 307 private final @KeyProperties.PurposeEnum int mPurposes; 308 private final @KeyProperties.DigestEnum String[] mDigests; 309 private final @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests; 310 private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings; 311 private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings; 312 private final @KeyProperties.BlockModeEnum String[] mBlockModes; 313 private final boolean mRandomizedEncryptionRequired; 314 private final boolean mUserAuthenticationRequired; 315 private final int mUserAuthenticationValidityDurationSeconds; 316 private final @KeyProperties.AuthEnum int mUserAuthenticationType; 317 private final boolean mUserPresenceRequired; 318 private final byte[] mAttestationChallenge; 319 private final boolean mDevicePropertiesAttestationIncluded; 320 private final int[] mAttestationIds; 321 private final boolean mUniqueIdIncluded; 322 private final boolean mUserAuthenticationValidWhileOnBody; 323 private final boolean mInvalidatedByBiometricEnrollment; 324 private final boolean mIsStrongBoxBacked; 325 private final boolean mUserConfirmationRequired; 326 private final boolean mUnlockedDeviceRequired; 327 private final boolean mCriticalToDeviceEncryption; 328 private final int mMaxUsageCount; 329 private final String mAttestKeyAlias; 330 private final long mBoundToSecureUserId; 331 332 /* 333 * ***NOTE***: All new fields MUST also be added to the following: 334 * ParcelableKeyGenParameterSpec class. 335 * The KeyGenParameterSpec.Builder constructor that takes a KeyGenParameterSpec 336 */ 337 338 /** 339 * @hide should be built with Builder 340 */ KeyGenParameterSpec( String keyStoreAlias, @KeyProperties.Namespace int namespace, int keySize, AlgorithmParameterSpec spec, X500Principal certificateSubject, BigInteger certificateSerialNumber, Date certificateNotBefore, Date certificateNotAfter, Date keyValidityStart, Date keyValidityForOriginationEnd, Date keyValidityForConsumptionEnd, @KeyProperties.PurposeEnum int purposes, @KeyProperties.DigestEnum String[] digests, @KeyProperties.DigestEnum Set<String> mgf1Digests, @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings, @KeyProperties.SignaturePaddingEnum String[] signaturePaddings, @KeyProperties.BlockModeEnum String[] blockModes, boolean randomizedEncryptionRequired, boolean userAuthenticationRequired, int userAuthenticationValidityDurationSeconds, @KeyProperties.AuthEnum int userAuthenticationType, boolean userPresenceRequired, byte[] attestationChallenge, boolean devicePropertiesAttestationIncluded, @NonNull int[] attestationIds, boolean uniqueIdIncluded, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment, boolean isStrongBoxBacked, boolean userConfirmationRequired, boolean unlockedDeviceRequired, boolean criticalToDeviceEncryption, int maxUsageCount, String attestKeyAlias, long boundToSecureUserId)341 public KeyGenParameterSpec( 342 String keyStoreAlias, 343 @KeyProperties.Namespace int namespace, 344 int keySize, 345 AlgorithmParameterSpec spec, 346 X500Principal certificateSubject, 347 BigInteger certificateSerialNumber, 348 Date certificateNotBefore, 349 Date certificateNotAfter, 350 Date keyValidityStart, 351 Date keyValidityForOriginationEnd, 352 Date keyValidityForConsumptionEnd, 353 @KeyProperties.PurposeEnum int purposes, 354 @KeyProperties.DigestEnum String[] digests, 355 @KeyProperties.DigestEnum Set<String> mgf1Digests, 356 @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings, 357 @KeyProperties.SignaturePaddingEnum String[] signaturePaddings, 358 @KeyProperties.BlockModeEnum String[] blockModes, 359 boolean randomizedEncryptionRequired, 360 boolean userAuthenticationRequired, 361 int userAuthenticationValidityDurationSeconds, 362 @KeyProperties.AuthEnum int userAuthenticationType, 363 boolean userPresenceRequired, 364 byte[] attestationChallenge, 365 boolean devicePropertiesAttestationIncluded, 366 @NonNull int[] attestationIds, 367 boolean uniqueIdIncluded, 368 boolean userAuthenticationValidWhileOnBody, 369 boolean invalidatedByBiometricEnrollment, 370 boolean isStrongBoxBacked, 371 boolean userConfirmationRequired, 372 boolean unlockedDeviceRequired, 373 boolean criticalToDeviceEncryption, 374 int maxUsageCount, 375 String attestKeyAlias, 376 long boundToSecureUserId) { 377 if (TextUtils.isEmpty(keyStoreAlias)) { 378 throw new IllegalArgumentException("keyStoreAlias must not be empty"); 379 } 380 381 if (certificateSubject == null) { 382 if (attestationChallenge == null) { 383 certificateSubject = DEFAULT_SELF_SIGNED_CERT_SUBJECT; 384 } else { 385 certificateSubject = DEFAULT_ATTESTATION_CERT_SUBJECT; 386 } 387 } 388 if (certificateNotBefore == null) { 389 certificateNotBefore = DEFAULT_CERT_NOT_BEFORE; 390 } 391 if (certificateNotAfter == null) { 392 certificateNotAfter = DEFAULT_CERT_NOT_AFTER; 393 } 394 if (certificateSerialNumber == null) { 395 certificateSerialNumber = DEFAULT_CERT_SERIAL_NUMBER; 396 } 397 398 if (certificateNotAfter.before(certificateNotBefore)) { 399 throw new IllegalArgumentException("certificateNotAfter < certificateNotBefore"); 400 } 401 402 mKeystoreAlias = keyStoreAlias; 403 mNamespace = namespace; 404 mKeySize = keySize; 405 mSpec = spec; 406 mCertificateSubject = certificateSubject; 407 mCertificateSerialNumber = certificateSerialNumber; 408 mCertificateNotBefore = Utils.cloneIfNotNull(certificateNotBefore); 409 mCertificateNotAfter = Utils.cloneIfNotNull(certificateNotAfter); 410 mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart); 411 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd); 412 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd); 413 mPurposes = purposes; 414 mDigests = ArrayUtils.cloneIfNotEmpty(digests); 415 // No need to copy the input parameter because the Builder class passes in an immutable 416 // collection. 417 mMgf1Digests = mgf1Digests != null ? mgf1Digests : Collections.emptySet(); 418 mEncryptionPaddings = 419 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings)); 420 mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings)); 421 mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes)); 422 mRandomizedEncryptionRequired = randomizedEncryptionRequired; 423 mUserAuthenticationRequired = userAuthenticationRequired; 424 mUserPresenceRequired = userPresenceRequired; 425 mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds; 426 mUserAuthenticationType = userAuthenticationType; 427 mAttestationChallenge = Utils.cloneIfNotNull(attestationChallenge); 428 mDevicePropertiesAttestationIncluded = devicePropertiesAttestationIncluded; 429 mAttestationIds = attestationIds; 430 mUniqueIdIncluded = uniqueIdIncluded; 431 mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody; 432 mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment; 433 mIsStrongBoxBacked = isStrongBoxBacked; 434 mUserConfirmationRequired = userConfirmationRequired; 435 mUnlockedDeviceRequired = unlockedDeviceRequired; 436 mCriticalToDeviceEncryption = criticalToDeviceEncryption; 437 mMaxUsageCount = maxUsageCount; 438 mAttestKeyAlias = attestKeyAlias; 439 mBoundToSecureUserId = boundToSecureUserId; 440 } 441 442 /** 443 * Returns the alias that will be used in the {@code java.security.KeyStore} 444 * in conjunction with the {@code AndroidKeyStore}. 445 */ 446 @NonNull getKeystoreAlias()447 public String getKeystoreAlias() { 448 return mKeystoreAlias; 449 } 450 451 /** 452 * Returns the UID which will own the key. {@code -1} is an alias for the UID of the current 453 * process. 454 * 455 * @deprecated See deprecation message on {@link KeyGenParameterSpec.Builder#setUid(int)}. 456 * Known namespaces will be translated to their legacy UIDs. Unknown 457 * Namespaces will yield {@link IllegalStateException}. 458 * 459 * @hide 460 */ 461 @UnsupportedAppUsage 462 @Deprecated getUid()463 public int getUid() { 464 try { 465 return KeyProperties.namespaceToLegacyUid(mNamespace); 466 } catch (IllegalArgumentException e) { 467 throw new IllegalStateException("getUid called on KeyGenParameterSpec with non legacy" 468 + " keystore namespace.", e); 469 } 470 } 471 472 /** 473 * Returns the target namespace for the key. 474 * See {@link KeyGenParameterSpec.Builder#setNamespace(int)}. 475 * 476 * @return The numeric namespace as configured in the keystore2_key_contexts files of Android's 477 * SEPolicy. 478 * See <a href="https://source.android.com/security/keystore#access-control"> 479 * Keystore 2.0 access control</a> 480 * @hide 481 */ 482 @SystemApi getNamespace()483 public @KeyProperties.Namespace int getNamespace() { 484 return mNamespace; 485 } 486 487 /** 488 * Returns the requested key size. If {@code -1}, the size should be looked up from 489 * {@link #getAlgorithmParameterSpec()}, if provided, otherwise an algorithm-specific default 490 * size should be used. 491 */ getKeySize()492 public int getKeySize() { 493 return mKeySize; 494 } 495 496 /** 497 * Returns the key algorithm-specific {@link AlgorithmParameterSpec} that will be used for 498 * creation of the key or {@code null} if algorithm-specific defaults should be used. 499 */ 500 @Nullable getAlgorithmParameterSpec()501 public AlgorithmParameterSpec getAlgorithmParameterSpec() { 502 return mSpec; 503 } 504 505 /** 506 * Returns the subject distinguished name to be used on the X.509 certificate that will be put 507 * in the {@link java.security.KeyStore}. 508 */ 509 @NonNull getCertificateSubject()510 public X500Principal getCertificateSubject() { 511 return mCertificateSubject; 512 } 513 514 /** 515 * Returns the serial number to be used on the X.509 certificate that will be put in the 516 * {@link java.security.KeyStore}. 517 */ 518 @NonNull getCertificateSerialNumber()519 public BigInteger getCertificateSerialNumber() { 520 return mCertificateSerialNumber; 521 } 522 523 /** 524 * Returns the start date to be used on the X.509 certificate that will be put in the 525 * {@link java.security.KeyStore}. 526 */ 527 @NonNull getCertificateNotBefore()528 public Date getCertificateNotBefore() { 529 return Utils.cloneIfNotNull(mCertificateNotBefore); 530 } 531 532 /** 533 * Returns the end date to be used on the X.509 certificate that will be put in the 534 * {@link java.security.KeyStore}. 535 */ 536 @NonNull getCertificateNotAfter()537 public Date getCertificateNotAfter() { 538 return Utils.cloneIfNotNull(mCertificateNotAfter); 539 } 540 541 /** 542 * Returns the time instant before which the key is not yet valid or {@code null} if not 543 * restricted. 544 */ 545 @Nullable getKeyValidityStart()546 public Date getKeyValidityStart() { 547 return Utils.cloneIfNotNull(mKeyValidityStart); 548 } 549 550 /** 551 * Returns the time instant after which the key is no longer valid for decryption and 552 * verification or {@code null} if not restricted. 553 */ 554 @Nullable getKeyValidityForConsumptionEnd()555 public Date getKeyValidityForConsumptionEnd() { 556 return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd); 557 } 558 559 /** 560 * Returns the time instant after which the key is no longer valid for encryption and signing 561 * or {@code null} if not restricted. 562 */ 563 @Nullable getKeyValidityForOriginationEnd()564 public Date getKeyValidityForOriginationEnd() { 565 return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd); 566 } 567 568 /** 569 * Returns the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used. 570 * Attempts to use the key for any other purpose will be rejected. 571 * 572 * <p>See {@link KeyProperties}.{@code PURPOSE} flags. 573 */ getPurposes()574 public @KeyProperties.PurposeEnum int getPurposes() { 575 return mPurposes; 576 } 577 578 /** 579 * Returns the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384} with which the 580 * key can be used. 581 * 582 * <p>See {@link KeyProperties}.{@code DIGEST} constants. 583 * 584 * @throws IllegalStateException if this set has not been specified. 585 * 586 * @see #isDigestsSpecified() 587 */ 588 @NonNull getDigests()589 public @KeyProperties.DigestEnum String[] getDigests() { 590 if (mDigests == null) { 591 throw new IllegalStateException("Digests not specified"); 592 } 593 return ArrayUtils.cloneIfNotEmpty(mDigests); 594 } 595 596 /** 597 * Returns {@code true} if the set of digest algorithms with which the key can be used has been 598 * specified. 599 * 600 * @see #getDigests() 601 */ 602 @NonNull isDigestsSpecified()603 public boolean isDigestsSpecified() { 604 return mDigests != null; 605 } 606 607 /** 608 * Returns the set of digests that can be used by the MGF1 mask generation function 609 * (e.g., {@code SHA-256}, {@code SHA-384}) with the key. Useful with the {@code RSA-OAEP} 610 * scheme. 611 * If not explicitly specified during key generation, the default {@code SHA-1} digest is 612 * used and may be specified when using the key. 613 * 614 * <p>See {@link KeyProperties}.{@code DIGEST} constants. 615 * 616 * @throws IllegalStateException if this set has not been specified. 617 * 618 * @see #isMgf1DigestsSpecified() 619 */ 620 @NonNull 621 @FlaggedApi(android.security.Flags.FLAG_MGF1_DIGEST_SETTER_V2) getMgf1Digests()622 public @KeyProperties.DigestEnum Set<String> getMgf1Digests() { 623 if (mMgf1Digests.isEmpty()) { 624 throw new IllegalStateException("Mask generation function (MGF) not specified"); 625 } 626 return new HashSet(mMgf1Digests); 627 } 628 629 /** 630 * Returns {@code true} if the set of digests for the MGF1 mask generation function, 631 * with which the key can be used, has been specified. Useful with the {@code RSA-OAEP} scheme. 632 * 633 * @see #getMgf1Digests() 634 */ 635 @NonNull 636 @FlaggedApi(android.security.Flags.FLAG_MGF1_DIGEST_SETTER_V2) isMgf1DigestsSpecified()637 public boolean isMgf1DigestsSpecified() { 638 return !mMgf1Digests.isEmpty(); 639 } 640 641 /** 642 * Returns the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OEAPPadding}, 643 * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when 644 * encrypting/decrypting. Attempts to use the key with any other padding scheme will be 645 * rejected. 646 * 647 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants. 648 */ 649 @NonNull getEncryptionPaddings()650 public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() { 651 return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings); 652 } 653 654 /** 655 * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key 656 * can be used when signing/verifying. Attempts to use the key with any other padding scheme 657 * will be rejected. 658 * 659 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants. 660 */ 661 @NonNull getSignaturePaddings()662 public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() { 663 return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings); 664 } 665 666 /** 667 * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used 668 * when encrypting/decrypting. Attempts to use the key with any other block modes will be 669 * rejected. 670 * 671 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants. 672 */ 673 @NonNull getBlockModes()674 public @KeyProperties.BlockModeEnum String[] getBlockModes() { 675 return ArrayUtils.cloneIfNotEmpty(mBlockModes); 676 } 677 678 /** 679 * Returns {@code true} if encryption using this key must be sufficiently randomized to produce 680 * different ciphertexts for the same plaintext every time. The formal cryptographic property 681 * being required is <em>indistinguishability under chosen-plaintext attack ({@code 682 * IND-CPA})</em>. This property is important because it mitigates several classes of 683 * weaknesses due to which ciphertext may leak information about plaintext. For example, if a 684 * given plaintext always produces the same ciphertext, an attacker may see the repeated 685 * ciphertexts and be able to deduce something about the plaintext. 686 */ isRandomizedEncryptionRequired()687 public boolean isRandomizedEncryptionRequired() { 688 return mRandomizedEncryptionRequired; 689 } 690 691 /** 692 * Returns {@code true} if the key is authorized to be used only if the user has been 693 * authenticated. 694 * 695 * <p>This authorization applies only to secret key and private key operations. Public key 696 * operations are not restricted. 697 * 698 * @see #getUserAuthenticationValidityDurationSeconds() 699 * @see Builder#setUserAuthenticationRequired(boolean) 700 */ isUserAuthenticationRequired()701 public boolean isUserAuthenticationRequired() { 702 return mUserAuthenticationRequired; 703 } 704 705 /** 706 * Returns {@code true} if the key is authorized to be used only for messages confirmed by the 707 * user. 708 * 709 * Confirmation is separate from user authentication (see 710 * {@link Builder#setUserAuthenticationRequired(boolean)}). Keys can be created that require 711 * confirmation but not user authentication, or user authentication but not confirmation, or 712 * both. Confirmation verifies that some user with physical possession of the device has 713 * approved a displayed message. User authentication verifies that the correct user is present 714 * and has authenticated. 715 * 716 * <p>This authorization applies only to secret key and private key operations. Public key 717 * operations are not restricted. 718 * 719 * @see Builder#setUserConfirmationRequired(boolean) 720 */ isUserConfirmationRequired()721 public boolean isUserConfirmationRequired() { 722 return mUserConfirmationRequired; 723 } 724 725 /** 726 * Gets the duration of time (seconds) for which this key is authorized to be used after the 727 * user is successfully authenticated. This has effect only if user authentication is required 728 * (see {@link #isUserAuthenticationRequired()}). 729 * 730 * <p>This authorization applies only to secret key and private key operations. Public key 731 * operations are not restricted. 732 * 733 * @return duration in seconds or {@code -1} if authentication is required for every use of the 734 * key. 735 * 736 * @see #isUserAuthenticationRequired() 737 * @see Builder#setUserAuthenticationValidityDurationSeconds(int) 738 */ getUserAuthenticationValidityDurationSeconds()739 public int getUserAuthenticationValidityDurationSeconds() { 740 return mUserAuthenticationValidityDurationSeconds; 741 } 742 743 /** 744 * Gets the modes of authentication that can authorize use of this key. This has effect only if 745 * user authentication is required (see {@link #isUserAuthenticationRequired()}). 746 * 747 * <p>This authorization applies only to secret key and private key operations. Public key 748 * operations are not restricted. 749 * 750 * @return integer representing the bitwse OR of all acceptable authentication types for the 751 * key. 752 * 753 * @see #isUserAuthenticationRequired() 754 * @see Builder#setUserAuthenticationParameters(int, int) 755 */ getUserAuthenticationType()756 public @KeyProperties.AuthEnum int getUserAuthenticationType() { 757 return mUserAuthenticationType; 758 } 759 /** 760 * Returns {@code true} if the key is authorized to be used only if a test of user presence has 761 * been performed between the {@code Signature.initSign()} and {@code Signature.sign()} calls. 762 * It requires that the KeyStore implementation have a direct way to validate the user presence 763 * for example a KeyStore hardware backed strongbox can use a button press that is observable 764 * in hardware. A test for user presence is tangential to authentication. The test can be part 765 * of an authentication step as long as this step can be validated by the hardware protecting 766 * the key and cannot be spoofed. For example, a physical button press can be used as a test of 767 * user presence if the other pins connected to the button are not able to simulate a button 768 * press. There must be no way for the primary processor to fake a button press, or that 769 * button must not be used as a test of user presence. 770 */ isUserPresenceRequired()771 public boolean isUserPresenceRequired() { 772 return mUserPresenceRequired; 773 } 774 775 /** 776 * Returns the attestation challenge value that will be placed in attestation certificate for 777 * this key pair. 778 * 779 * <p>If this method returns non-{@code null}, the public key certificate for this key pair will 780 * contain an extension that describes the details of the key's configuration and 781 * authorizations, including the content of the attestation challenge value. If the key is in 782 * secure hardware, and if the secure hardware supports attestation, the certificate will be 783 * signed by a chain of certificates rooted at a trustworthy CA key. Otherwise the chain will 784 * be rooted at an untrusted certificate. 785 * 786 * <p>If this method returns {@code null}, and the spec is used to generate an asymmetric (RSA 787 * or EC) key pair, the public key will have a self-signed certificate if it has purpose {@link 788 * KeyProperties#PURPOSE_SIGN}. If does not have purpose {@link KeyProperties#PURPOSE_SIGN}, it 789 * will have a fake certificate. 790 * 791 * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a 792 * KeyGenParameterSpec with getAttestationChallenge returning non-null is used to generate a 793 * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw 794 * {@link java.security.InvalidAlgorithmParameterException}. 795 * 796 * @see Builder#setAttestationChallenge(byte[]) 797 */ getAttestationChallenge()798 public byte[] getAttestationChallenge() { 799 return Utils.cloneIfNotNull(mAttestationChallenge); 800 } 801 802 /** 803 * Returns {@code true} if attestation for the base device properties ({@link Build#BRAND}, 804 * {@link Build#DEVICE}, {@link Build#MANUFACTURER}, {@link Build#MODEL}, {@link Build#PRODUCT}) 805 * was requested to be added in the attestation certificate for the generated key. 806 * 807 * {@link javax.crypto.KeyGenerator#generateKey()} will throw 808 * {@link java.security.ProviderException} if device properties attestation fails or is not 809 * supported. 810 * 811 * @see Builder#setDevicePropertiesAttestationIncluded(boolean) 812 */ isDevicePropertiesAttestationIncluded()813 public boolean isDevicePropertiesAttestationIncluded() { 814 return mDevicePropertiesAttestationIncluded; 815 } 816 817 /** 818 * @hide 819 * Allows the caller to specify device IDs to be attested to in the certificate for the 820 * generated key pair. These values are the enums specified in 821 * {@link android.security.keystore.AttestationUtils} 822 * 823 * @see android.security.keystore.AttestationUtils#ID_TYPE_SERIAL 824 * @see android.security.keystore.AttestationUtils#ID_TYPE_IMEI 825 * @see android.security.keystore.AttestationUtils#ID_TYPE_MEID 826 * @see android.security.keystore.AttestationUtils#USE_INDIVIDUAL_ATTESTATION 827 * 828 * @return integer array representing the requested device IDs to attest. 829 */ 830 @SystemApi getAttestationIds()831 public @NonNull int[] getAttestationIds() { 832 return mAttestationIds.clone(); 833 } 834 835 /** 836 * @hide This is a system-only API 837 * 838 * Returns {@code true} if the attestation certificate will contain a unique ID field. 839 */ 840 @UnsupportedAppUsage isUniqueIdIncluded()841 public boolean isUniqueIdIncluded() { 842 return mUniqueIdIncluded; 843 } 844 845 /** 846 * Returns {@code true} if the key will remain authorized only until the device is removed from 847 * the user's body, up to the validity duration. This option has no effect on keys that don't 848 * have an authentication validity duration, and has no effect if the device lacks an on-body 849 * sensor. 850 * 851 * <p>Authorization applies only to secret key and private key operations. Public key operations 852 * are not restricted. 853 * 854 * @see #isUserAuthenticationRequired() 855 * @see #getUserAuthenticationValidityDurationSeconds() 856 * @see Builder#setUserAuthenticationValidWhileOnBody(boolean) 857 */ isUserAuthenticationValidWhileOnBody()858 public boolean isUserAuthenticationValidWhileOnBody() { 859 return mUserAuthenticationValidWhileOnBody; 860 } 861 862 /** 863 * Returns {@code true} if the key is irreversibly invalidated when a new biometric is 864 * enrolled or all enrolled biometrics are removed. This has effect only for keys that 865 * require biometric user authentication for every use. 866 * 867 * @see #isUserAuthenticationRequired() 868 * @see #getUserAuthenticationValidityDurationSeconds() 869 * @see Builder#setInvalidatedByBiometricEnrollment(boolean) 870 */ isInvalidatedByBiometricEnrollment()871 public boolean isInvalidatedByBiometricEnrollment() { 872 return mInvalidatedByBiometricEnrollment; 873 } 874 875 /** 876 * Returns {@code true} if the key is protected by a Strongbox security chip. 877 */ isStrongBoxBacked()878 public boolean isStrongBoxBacked() { 879 return mIsStrongBoxBacked; 880 } 881 882 /** 883 * Returns {@code true} if the key is authorized to be used only while the device is unlocked. 884 * 885 * @see Builder#setUnlockedDeviceRequired(boolean) 886 */ isUnlockedDeviceRequired()887 public boolean isUnlockedDeviceRequired() { 888 return mUnlockedDeviceRequired; 889 } 890 891 /** 892 * Return the secure user id that this key should be bound to. 893 * 894 * Normally an authentication-bound key is tied to the secure user id of the current user 895 * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the authenticator 896 * id of the current biometric set for keys requiring explicit biometric authorization). 897 * If this parameter is set (this method returning non-zero value), the key should be tied to 898 * the specified secure user id, overriding the logic above. 899 * 900 * This is only applicable when {@link #isUserAuthenticationRequired} is {@code true} 901 * 902 * @hide 903 */ getBoundToSpecificSecureUserId()904 public long getBoundToSpecificSecureUserId() { 905 return mBoundToSecureUserId; 906 } 907 908 /** 909 * Returns whether this key is critical to the device encryption flow. 910 * 911 * @see Builder#setCriticalToDeviceEncryption(boolean) 912 * @hide 913 */ isCriticalToDeviceEncryption()914 public boolean isCriticalToDeviceEncryption() { 915 return mCriticalToDeviceEncryption; 916 } 917 918 /** 919 * Returns the maximum number of times the limited use key is allowed to be used or 920 * {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there’s no restriction on the number of 921 * times the key can be used. 922 * 923 * @see Builder#setMaxUsageCount(int) 924 */ getMaxUsageCount()925 public int getMaxUsageCount() { 926 return mMaxUsageCount; 927 } 928 929 /** 930 * Returns the alias of the attestation key that will be used to sign the attestation 931 * certificate of the generated key. Note that an attestation certificate will only be 932 * generated if an attestation challenge is set. 933 * 934 * @see Builder#setAttestKeyAlias(String) 935 */ 936 @Nullable getAttestKeyAlias()937 public String getAttestKeyAlias() { 938 return mAttestKeyAlias; 939 } 940 941 /** 942 * Builder of {@link KeyGenParameterSpec} instances. 943 */ 944 public final static class Builder { 945 private final String mKeystoreAlias; 946 private @KeyProperties.PurposeEnum int mPurposes; 947 948 private @KeyProperties.Namespace int mNamespace = KeyProperties.NAMESPACE_APPLICATION; 949 private int mKeySize = -1; 950 private AlgorithmParameterSpec mSpec; 951 private X500Principal mCertificateSubject; 952 private BigInteger mCertificateSerialNumber; 953 private Date mCertificateNotBefore; 954 private Date mCertificateNotAfter; 955 private Date mKeyValidityStart; 956 private Date mKeyValidityForOriginationEnd; 957 private Date mKeyValidityForConsumptionEnd; 958 private @KeyProperties.DigestEnum String[] mDigests; 959 private @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests = 960 Collections.emptySet(); 961 private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings; 962 private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings; 963 private @KeyProperties.BlockModeEnum String[] mBlockModes; 964 private boolean mRandomizedEncryptionRequired = true; 965 private boolean mUserAuthenticationRequired; 966 private int mUserAuthenticationValidityDurationSeconds = 0; 967 private @KeyProperties.AuthEnum int mUserAuthenticationType = 968 KeyProperties.AUTH_BIOMETRIC_STRONG; 969 private boolean mUserPresenceRequired = false; 970 private byte[] mAttestationChallenge = null; 971 private boolean mDevicePropertiesAttestationIncluded = false; 972 private int[] mAttestationIds = new int[0]; 973 private boolean mUniqueIdIncluded = false; 974 private boolean mUserAuthenticationValidWhileOnBody; 975 private boolean mInvalidatedByBiometricEnrollment = true; 976 private boolean mIsStrongBoxBacked = false; 977 private boolean mUserConfirmationRequired; 978 private boolean mUnlockedDeviceRequired = false; 979 private boolean mCriticalToDeviceEncryption = false; 980 private int mMaxUsageCount = KeyProperties.UNRESTRICTED_USAGE_COUNT; 981 private String mAttestKeyAlias = null; 982 private long mBoundToSecureUserId = GateKeeper.INVALID_SECURE_USER_ID; 983 984 /** 985 * Creates a new instance of the {@code Builder}. 986 * 987 * @param keystoreAlias alias of the entry in which the generated key will appear in 988 * Android KeyStore. Must not be empty. 989 * @param purposes set of purposes (e.g., encrypt, decrypt, sign) for which the key can be 990 * used. Attempts to use the key for any other purpose will be rejected. 991 * 992 * <p>See {@link KeyProperties}.{@code PURPOSE} flags. 993 */ Builder(@onNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes)994 public Builder(@NonNull String keystoreAlias, @KeyProperties.PurposeEnum int purposes) { 995 if (keystoreAlias == null) { 996 throw new NullPointerException("keystoreAlias == null"); 997 } else if (keystoreAlias.isEmpty()) { 998 throw new IllegalArgumentException("keystoreAlias must not be empty"); 999 } 1000 mKeystoreAlias = keystoreAlias; 1001 mPurposes = purposes; 1002 } 1003 1004 /** 1005 * A Builder constructor taking in an already-built KeyGenParameterSpec, useful for 1006 * changing values of the KeyGenParameterSpec quickly. 1007 * @hide Should be used internally only. 1008 */ Builder(@onNull KeyGenParameterSpec sourceSpec)1009 public Builder(@NonNull KeyGenParameterSpec sourceSpec) { 1010 this(sourceSpec.getKeystoreAlias(), sourceSpec.getPurposes()); 1011 mNamespace = sourceSpec.getNamespace(); 1012 mKeySize = sourceSpec.getKeySize(); 1013 mSpec = sourceSpec.getAlgorithmParameterSpec(); 1014 mCertificateSubject = sourceSpec.getCertificateSubject(); 1015 mCertificateSerialNumber = sourceSpec.getCertificateSerialNumber(); 1016 mCertificateNotBefore = sourceSpec.getCertificateNotBefore(); 1017 mCertificateNotAfter = sourceSpec.getCertificateNotAfter(); 1018 mKeyValidityStart = sourceSpec.getKeyValidityStart(); 1019 mKeyValidityForOriginationEnd = sourceSpec.getKeyValidityForOriginationEnd(); 1020 mKeyValidityForConsumptionEnd = sourceSpec.getKeyValidityForConsumptionEnd(); 1021 mPurposes = sourceSpec.getPurposes(); 1022 if (sourceSpec.isDigestsSpecified()) { 1023 mDigests = sourceSpec.getDigests(); 1024 } 1025 if (sourceSpec.isMgf1DigestsSpecified()) { 1026 mMgf1Digests = sourceSpec.getMgf1Digests(); 1027 } 1028 mEncryptionPaddings = sourceSpec.getEncryptionPaddings(); 1029 mSignaturePaddings = sourceSpec.getSignaturePaddings(); 1030 mBlockModes = sourceSpec.getBlockModes(); 1031 mRandomizedEncryptionRequired = sourceSpec.isRandomizedEncryptionRequired(); 1032 mUserAuthenticationRequired = sourceSpec.isUserAuthenticationRequired(); 1033 mUserAuthenticationValidityDurationSeconds = 1034 sourceSpec.getUserAuthenticationValidityDurationSeconds(); 1035 mUserAuthenticationType = sourceSpec.getUserAuthenticationType(); 1036 mUserPresenceRequired = sourceSpec.isUserPresenceRequired(); 1037 mAttestationChallenge = sourceSpec.getAttestationChallenge(); 1038 mDevicePropertiesAttestationIncluded = 1039 sourceSpec.isDevicePropertiesAttestationIncluded(); 1040 mAttestationIds = sourceSpec.getAttestationIds(); 1041 mUniqueIdIncluded = sourceSpec.isUniqueIdIncluded(); 1042 mUserAuthenticationValidWhileOnBody = sourceSpec.isUserAuthenticationValidWhileOnBody(); 1043 mInvalidatedByBiometricEnrollment = sourceSpec.isInvalidatedByBiometricEnrollment(); 1044 mIsStrongBoxBacked = sourceSpec.isStrongBoxBacked(); 1045 mUserConfirmationRequired = sourceSpec.isUserConfirmationRequired(); 1046 mUnlockedDeviceRequired = sourceSpec.isUnlockedDeviceRequired(); 1047 mCriticalToDeviceEncryption = sourceSpec.isCriticalToDeviceEncryption(); 1048 mMaxUsageCount = sourceSpec.getMaxUsageCount(); 1049 mAttestKeyAlias = sourceSpec.getAttestKeyAlias(); 1050 mBoundToSecureUserId = sourceSpec.getBoundToSpecificSecureUserId(); 1051 } 1052 1053 /** 1054 * Sets the UID which will own the key. 1055 * 1056 * Such cross-UID access is permitted to a few system UIDs and only to a few other UIDs 1057 * (e.g., Wi-Fi, VPN) all of which are system. 1058 * 1059 * @param uid UID or {@code -1} for the UID of the current process. 1060 * 1061 * @deprecated Setting the UID of the target namespace is based on a hardcoded 1062 * hack in the Keystore service. This is no longer supported with Keystore 2.0/Android S. 1063 * Instead, dedicated non UID based namespaces can be configured in SEPolicy using 1064 * the keystore2_key_contexts files. The functionality of this method will be supported 1065 * by mapping knows special UIDs, such as WIFI, to the newly configured SELinux based 1066 * namespaces. Unknown UIDs will yield {@link IllegalArgumentException}. 1067 * 1068 * @hide 1069 */ 1070 @SystemApi 1071 @NonNull 1072 @Deprecated setUid(int uid)1073 public Builder setUid(int uid) { 1074 mNamespace = KeyProperties.legacyUidToNamespace(uid); 1075 return this; 1076 } 1077 1078 /** 1079 * Set the designated SELinux namespace that the key shall live in. The caller must 1080 * have sufficient permissions to install a key in the given namespace. Namespaces 1081 * can be created using SEPolicy. The keystore2_key_contexts files map numeric 1082 * namespaces to SELinux labels, and SEPolicy can be used to grant access to these 1083 * namespaces to the desired target context. This is the preferred way to share 1084 * keys between system and vendor components, e.g., WIFI settings and WPA supplicant. 1085 * 1086 * @param namespace Numeric SELinux namespace as configured in keystore2_key_contexts 1087 * of Android's SEPolicy. 1088 * See <a href="https://source.android.com/security/keystore#access-control"> 1089 * Keystore 2.0 access control</a> 1090 * @return this Builder object. 1091 * 1092 * @hide 1093 */ 1094 @SystemApi 1095 @NonNull setNamespace(@eyProperties.Namespace int namespace)1096 public Builder setNamespace(@KeyProperties.Namespace int namespace) { 1097 mNamespace = namespace; 1098 return this; 1099 } 1100 1101 /** 1102 * Sets the size (in bits) of the key to be generated. For instance, for RSA keys this sets 1103 * the modulus size, for EC keys this selects a curve with a matching field size, and for 1104 * symmetric keys this sets the size of the bitstring which is their key material. 1105 * 1106 * <p>The default key size is specific to each key algorithm. If key size is not set 1107 * via this method, it should be looked up from the algorithm-specific parameters (if any) 1108 * provided via 1109 * {@link #setAlgorithmParameterSpec(AlgorithmParameterSpec) setAlgorithmParameterSpec}. 1110 */ 1111 @NonNull setKeySize(int keySize)1112 public Builder setKeySize(int keySize) { 1113 if (keySize < 0) { 1114 throw new IllegalArgumentException("keySize < 0"); 1115 } 1116 mKeySize = keySize; 1117 return this; 1118 } 1119 1120 /** 1121 * Sets the algorithm-specific key generation parameters. For example, for RSA keys this may 1122 * be an instance of {@link java.security.spec.RSAKeyGenParameterSpec} whereas for EC keys 1123 * this may be an instance of {@link java.security.spec.ECGenParameterSpec}. 1124 * 1125 * <p>These key generation parameters must match other explicitly set parameters (if any), 1126 * such as key size. 1127 */ setAlgorithmParameterSpec(@onNull AlgorithmParameterSpec spec)1128 public Builder setAlgorithmParameterSpec(@NonNull AlgorithmParameterSpec spec) { 1129 if (spec == null) { 1130 throw new NullPointerException("spec == null"); 1131 } 1132 mSpec = spec; 1133 return this; 1134 } 1135 1136 /** 1137 * Sets the subject used for the certificate of the generated key pair. 1138 * 1139 * <p>By default, the subject is {@code CN=fake}. 1140 */ 1141 @NonNull setCertificateSubject(@onNull X500Principal subject)1142 public Builder setCertificateSubject(@NonNull X500Principal subject) { 1143 if (subject == null) { 1144 throw new NullPointerException("subject == null"); 1145 } 1146 mCertificateSubject = subject; 1147 return this; 1148 } 1149 1150 /** 1151 * Sets the serial number used for the certificate of the generated key pair. 1152 * To ensure compatibility with devices and certificate parsers, the value 1153 * should be 20 bytes or shorter (see RFC 5280 section 4.1.2.2). 1154 * 1155 * <p>By default, the serial number is {@code 1}. 1156 */ 1157 @NonNull setCertificateSerialNumber(@onNull BigInteger serialNumber)1158 public Builder setCertificateSerialNumber(@NonNull BigInteger serialNumber) { 1159 if (serialNumber == null) { 1160 throw new NullPointerException("serialNumber == null"); 1161 } 1162 mCertificateSerialNumber = serialNumber; 1163 return this; 1164 } 1165 1166 /** 1167 * Sets the start of the validity period for the certificate of the generated key pair. 1168 * 1169 * <p>By default, this date is {@code Jan 1 1970}. 1170 */ 1171 @NonNull setCertificateNotBefore(@onNull Date date)1172 public Builder setCertificateNotBefore(@NonNull Date date) { 1173 if (date == null) { 1174 throw new NullPointerException("date == null"); 1175 } 1176 mCertificateNotBefore = Utils.cloneIfNotNull(date); 1177 return this; 1178 } 1179 1180 /** 1181 * Sets the end of the validity period for the certificate of the generated key pair. 1182 * 1183 * <p>By default, this date is {@code Jan 1 2048}. 1184 */ 1185 @NonNull setCertificateNotAfter(@onNull Date date)1186 public Builder setCertificateNotAfter(@NonNull Date date) { 1187 if (date == null) { 1188 throw new NullPointerException("date == null"); 1189 } 1190 mCertificateNotAfter = Utils.cloneIfNotNull(date); 1191 return this; 1192 } 1193 1194 /** 1195 * Sets the time instant before which the key is not yet valid. 1196 * 1197 * <p>By default, the key is valid at any instant. 1198 * 1199 * @see #setKeyValidityEnd(Date) 1200 */ 1201 @NonNull setKeyValidityStart(Date startDate)1202 public Builder setKeyValidityStart(Date startDate) { 1203 mKeyValidityStart = Utils.cloneIfNotNull(startDate); 1204 return this; 1205 } 1206 1207 /** 1208 * Sets the time instant after which the key is no longer valid. 1209 * 1210 * <p>By default, the key is valid at any instant. 1211 * 1212 * @see #setKeyValidityStart(Date) 1213 * @see #setKeyValidityForConsumptionEnd(Date) 1214 * @see #setKeyValidityForOriginationEnd(Date) 1215 */ 1216 @NonNull setKeyValidityEnd(Date endDate)1217 public Builder setKeyValidityEnd(Date endDate) { 1218 setKeyValidityForOriginationEnd(endDate); 1219 setKeyValidityForConsumptionEnd(endDate); 1220 return this; 1221 } 1222 1223 /** 1224 * Sets the time instant after which the key is no longer valid for encryption and signing. 1225 * 1226 * <p>By default, the key is valid at any instant. 1227 * 1228 * @see #setKeyValidityForConsumptionEnd(Date) 1229 */ 1230 @NonNull setKeyValidityForOriginationEnd(Date endDate)1231 public Builder setKeyValidityForOriginationEnd(Date endDate) { 1232 mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(endDate); 1233 return this; 1234 } 1235 1236 /** 1237 * Sets the time instant after which the key is no longer valid for decryption and 1238 * verification. 1239 * 1240 * <p>By default, the key is valid at any instant. 1241 * 1242 * @see #setKeyValidityForOriginationEnd(Date) 1243 */ 1244 @NonNull setKeyValidityForConsumptionEnd(Date endDate)1245 public Builder setKeyValidityForConsumptionEnd(Date endDate) { 1246 mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(endDate); 1247 return this; 1248 } 1249 1250 /** 1251 * Sets the set of digests algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which 1252 * the key can be used. Attempts to use the key with any other digest algorithm will be 1253 * rejected. 1254 * 1255 * <p>This must be specified for signing/verification keys and RSA encryption/decryption 1256 * keys used with RSA OAEP padding scheme because these operations involve a digest. For 1257 * HMAC keys, the default is the digest associated with the key algorithm (e.g., 1258 * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized 1259 * for more than one digest. 1260 * 1261 * <p>For private keys used for TLS/SSL client or server authentication it is usually 1262 * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is 1263 * because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use 1264 * a private key to sign it. 1265 * 1266 * <p>See {@link KeyProperties}.{@code DIGEST} constants. 1267 */ 1268 @NonNull setDigests(@eyProperties.DigestEnum String... digests)1269 public Builder setDigests(@KeyProperties.DigestEnum String... digests) { 1270 mDigests = ArrayUtils.cloneIfNotEmpty(digests); 1271 return this; 1272 } 1273 1274 /** 1275 * Sets the set of hash functions (e.g., {@code SHA-256}, {@code SHA-384}) which could be 1276 * used by the mask generation function MGF1 (which is used for certain operations with 1277 * the key). Attempts to use the key with any other digest for the mask generation 1278 * function will be rejected. 1279 * 1280 * <p>This can only be specified for signing/verification keys and RSA encryption/decryption 1281 * keys used with RSA OAEP padding scheme because these operations involve a mask generation 1282 * function (MGF1) with a digest. 1283 * The default digest for MGF1 is {@code SHA-1}, which will be specified during key creation 1284 * time if no digests have been explicitly provided. 1285 * {@code null} may not be specified as a parameter to this method: It is not possible to 1286 * disable MGF1 digest, a default must be present for when the caller tries to use it. 1287 * 1288 * <p>When using the key, the caller may not specify any digests that were not provided 1289 * during key creation time. The caller may specify the default digest, {@code SHA-1}, if no 1290 * digests were explicitly provided during key creation (but it is not necessary to do so). 1291 * 1292 * <p>See {@link KeyProperties}.{@code DIGEST} constants. 1293 */ 1294 @NonNull 1295 @FlaggedApi(android.security.Flags.FLAG_MGF1_DIGEST_SETTER_V2) setMgf1Digests(@onNull @eyProperties.DigestEnum String... mgf1Digests)1296 public Builder setMgf1Digests(@NonNull @KeyProperties.DigestEnum String... mgf1Digests) { 1297 mMgf1Digests = Set.of(mgf1Digests); 1298 return this; 1299 } 1300 1301 /** 1302 * Sets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OAEPPadding}, 1303 * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when 1304 * encrypting/decrypting. Attempts to use the key with any other padding scheme will be 1305 * rejected. 1306 * 1307 * <p>This must be specified for keys which are used for encryption/decryption. 1308 * 1309 * <p>For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it 1310 * is usually necessary to authorize the use of no/any padding 1311 * ({@link KeyProperties#ENCRYPTION_PADDING_NONE}) and/or PKCS#1 encryption padding 1312 * ({@link KeyProperties#ENCRYPTION_PADDING_RSA_PKCS1}). This is because RSA decryption is 1313 * required by some cipher suites, and some stacks request decryption using no padding 1314 * whereas others request PKCS#1 padding. 1315 * 1316 * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants. 1317 */ 1318 @NonNull setEncryptionPaddings( @eyProperties.EncryptionPaddingEnum String... paddings)1319 public Builder setEncryptionPaddings( 1320 @KeyProperties.EncryptionPaddingEnum String... paddings) { 1321 mEncryptionPaddings = ArrayUtils.cloneIfNotEmpty(paddings); 1322 return this; 1323 } 1324 1325 /** 1326 * Sets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key 1327 * can be used when signing/verifying. Attempts to use the key with any other padding scheme 1328 * will be rejected. 1329 * 1330 * <p>This must be specified for RSA keys which are used for signing/verification. 1331 * 1332 * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants. 1333 */ 1334 @NonNull setSignaturePaddings( @eyProperties.SignaturePaddingEnum String... paddings)1335 public Builder setSignaturePaddings( 1336 @KeyProperties.SignaturePaddingEnum String... paddings) { 1337 mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(paddings); 1338 return this; 1339 } 1340 1341 /** 1342 * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be 1343 * used when encrypting/decrypting. Attempts to use the key with any other block modes will 1344 * be rejected. 1345 * 1346 * <p>This must be specified for symmetric encryption/decryption keys. 1347 * 1348 * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants. 1349 */ 1350 @NonNull setBlockModes(@eyProperties.BlockModeEnum String... blockModes)1351 public Builder setBlockModes(@KeyProperties.BlockModeEnum String... blockModes) { 1352 mBlockModes = ArrayUtils.cloneIfNotEmpty(blockModes); 1353 return this; 1354 } 1355 1356 /** 1357 * Sets whether encryption using this key must be sufficiently randomized to produce 1358 * different ciphertexts for the same plaintext every time. The formal cryptographic 1359 * property being required is <em>indistinguishability under chosen-plaintext attack 1360 * ({@code IND-CPA})</em>. This property is important because it mitigates several classes 1361 * of weaknesses due to which ciphertext may leak information about plaintext. For example, 1362 * if a given plaintext always produces the same ciphertext, an attacker may see the 1363 * repeated ciphertexts and be able to deduce something about the plaintext. 1364 * 1365 * <p>By default, {@code IND-CPA} is required. 1366 * 1367 * <p>When {@code IND-CPA} is required: 1368 * <ul> 1369 * <li>encryption/decryption transformation which do not offer {@code IND-CPA}, such as 1370 * {@code ECB} with a symmetric encryption algorithm, or RSA encryption/decryption without 1371 * padding, are prohibited;</li> 1372 * <li>in block modes which use an IV, such as {@code GCM}, {@code CBC}, and {@code CTR}, 1373 * caller-provided IVs are rejected when encrypting, to ensure that only random IVs are 1374 * used.</li> 1375 * </ul> 1376 * 1377 * <p>Before disabling this requirement, consider the following approaches instead: 1378 * <ul> 1379 * <li>If you are generating a random IV for encryption and then initializing a {@code} 1380 * Cipher using the IV, the solution is to let the {@code Cipher} generate a random IV 1381 * instead. This will occur if the {@code Cipher} is initialized for encryption without an 1382 * IV. The IV can then be queried via {@link Cipher#getIV()}.</li> 1383 * <li>If you are generating a non-random IV (e.g., an IV derived from something not fully 1384 * random, such as the name of the file being encrypted, or transaction ID, or password, 1385 * or a device identifier), consider changing your design to use a random IV which will then 1386 * be provided in addition to the ciphertext to the entities which need to decrypt the 1387 * ciphertext.</li> 1388 * <li>If you are using RSA encryption without padding, consider switching to encryption 1389 * padding schemes which offer {@code IND-CPA}, such as PKCS#1 or OAEP.</li> 1390 * </ul> 1391 */ 1392 @NonNull setRandomizedEncryptionRequired(boolean required)1393 public Builder setRandomizedEncryptionRequired(boolean required) { 1394 mRandomizedEncryptionRequired = required; 1395 return this; 1396 } 1397 1398 /** 1399 * Sets whether this key is authorized to be used only if the user has been authenticated. 1400 * 1401 * <p>By default, the key is authorized to be used regardless of whether the user has been 1402 * authenticated. 1403 * 1404 * <p>When user authentication is required: 1405 * <ul> 1406 * <li>The key can only be generated if secure lock screen is set up (see 1407 * {@link KeyguardManager#isDeviceSecure()}). Additionally, if the key requires that user 1408 * authentication takes place for every use of the key (see 1409 * {@link #setUserAuthenticationValidityDurationSeconds(int)}), at least one biometric 1410 * must be enrolled (see {@link BiometricManager#canAuthenticate()}).</li> 1411 * <li>The use of the key must be authorized by the user by authenticating to this Android 1412 * device using a subset of their secure lock screen credentials such as 1413 * password/PIN/pattern or biometric. 1414 * <a href="{@docRoot}training/articles/keystore.html#UserAuthentication">More 1415 * information</a>. 1416 * <li>The key will become <em>irreversibly invalidated</em> once the secure lock screen is 1417 * disabled (reconfigured to None, Swipe or other mode which does not authenticate the user) 1418 * or when the secure lock screen is forcibly reset (e.g., by a Device Administrator). 1419 * Additionally, if the key requires that user authentication takes place for every use of 1420 * the key, it is also irreversibly invalidated once a new biometric is enrolled or once\ 1421 * no more biometrics are enrolled, unless {@link 1422 * #setInvalidatedByBiometricEnrollment(boolean)} is used to allow validity after 1423 * enrollment, or {@code KeyProperties.AUTH_DEVICE_CREDENTIAL} is specified as part of 1424 * the parameters to {@link #setUserAuthenticationParameters}. 1425 * Attempts to initialize cryptographic operations using such keys will throw 1426 * {@link KeyPermanentlyInvalidatedException}.</li> 1427 * </ul> 1428 * 1429 * <p>This authorization applies only to secret key and private key operations. Public key 1430 * operations are not restricted. 1431 * 1432 * @see #setUserAuthenticationValidityDurationSeconds(int) 1433 * @see KeyguardManager#isDeviceSecure() 1434 * @see BiometricManager#canAuthenticate() 1435 */ 1436 @NonNull setUserAuthenticationRequired(boolean required)1437 public Builder setUserAuthenticationRequired(boolean required) { 1438 mUserAuthenticationRequired = required; 1439 return this; 1440 } 1441 1442 /** 1443 * Sets whether this key is authorized to be used only for messages confirmed by the 1444 * user. 1445 * 1446 * Confirmation is separate from user authentication (see 1447 * {@link #setUserAuthenticationRequired(boolean)}). Keys can be created that require 1448 * confirmation but not user authentication, or user authentication but not confirmation, 1449 * or both. Confirmation verifies that some user with physical possession of the device has 1450 * approved a displayed message. User authentication verifies that the correct user is 1451 * present and has authenticated. 1452 * 1453 * <p>This authorization applies only to secret key and private key operations. Public key 1454 * operations are not restricted. 1455 * 1456 * See {@link android.security.ConfirmationPrompt} class for 1457 * more details about user confirmations. 1458 */ 1459 @NonNull setUserConfirmationRequired(boolean required)1460 public Builder setUserConfirmationRequired(boolean required) { 1461 mUserConfirmationRequired = required; 1462 return this; 1463 } 1464 1465 /** 1466 * Sets the duration of time (seconds) for which this key is authorized to be used after the 1467 * user is successfully authenticated. This has effect if the key requires user 1468 * authentication for its use (see {@link #setUserAuthenticationRequired(boolean)}). 1469 * 1470 * <p>By default, if user authentication is required, it must take place for every use of 1471 * the key. 1472 * 1473 * <p>Cryptographic operations involving keys which require user authentication to take 1474 * place for every operation can only use biometric authentication. This is achieved by 1475 * initializing a cryptographic operation ({@link Signature}, {@link Cipher}, {@link Mac}) 1476 * with the key, wrapping it into a {@link BiometricPrompt.CryptoObject}, invoking 1477 * {@code BiometricPrompt.authenticate} with {@code CryptoObject}, and proceeding with 1478 * the cryptographic operation only if the authentication flow succeeds. 1479 * 1480 * <p>Cryptographic operations involving keys which are authorized to be used for a duration 1481 * of time after a successful user authentication event can only use secure lock screen 1482 * authentication. These cryptographic operations will throw 1483 * {@link UserNotAuthenticatedException} during initialization if the user needs to be 1484 * authenticated to proceed. This situation can be resolved by the user unlocking the secure 1485 * lock screen of the Android or by going through the confirm credential flow initiated by 1486 * {@link KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, CharSequence)}. 1487 * Once resolved, initializing a new cryptographic operation using this key (or any other 1488 * key which is authorized to be used for a fixed duration of time after user 1489 * authentication) should succeed provided the user authentication flow completed 1490 * successfully. 1491 * 1492 * @param seconds duration in seconds or {@code -1} if user authentication must take place 1493 * for every use of the key. 1494 * 1495 * @see #setUserAuthenticationRequired(boolean) 1496 * @see BiometricPrompt 1497 * @see BiometricPrompt.CryptoObject 1498 * @see KeyguardManager 1499 * @deprecated See {@link #setUserAuthenticationParameters(int, int)} 1500 */ 1501 @Deprecated 1502 @NonNull setUserAuthenticationValidityDurationSeconds( @ntRangefrom = -1) int seconds)1503 public Builder setUserAuthenticationValidityDurationSeconds( 1504 @IntRange(from = -1) int seconds) { 1505 if (seconds < -1) { 1506 throw new IllegalArgumentException("seconds must be -1 or larger"); 1507 } 1508 if (seconds == -1) { 1509 return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG); 1510 } 1511 return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL 1512 | KeyProperties.AUTH_BIOMETRIC_STRONG); 1513 } 1514 1515 /** 1516 * Sets the duration of time (seconds) and authorization type for which this key is 1517 * authorized to be used after the user is successfully authenticated. This has effect if 1518 * the key requires user authentication for its use (see 1519 * {@link #setUserAuthenticationRequired(boolean)}). 1520 * 1521 * <p>By default, if user authentication is required, it must take place for every use of 1522 * the key. 1523 * 1524 * <p>These cryptographic operations will throw {@link UserNotAuthenticatedException} during 1525 * initialization if the user needs to be authenticated to proceed. This situation can be 1526 * resolved by the user authenticating with the appropriate biometric or credential as 1527 * required by the key. See {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)} 1528 * and {@link BiometricManager.Authenticators}. 1529 * 1530 * <p>Once resolved, initializing a new cryptographic operation using this key (or any other 1531 * key which is authorized to be used for a fixed duration of time after user 1532 * authentication) should succeed provided the user authentication flow completed 1533 * successfully. 1534 * 1535 * @param timeout duration in seconds or {@code 0} if user authentication must take place 1536 * for every use of the key. 1537 * @param type set of authentication types which can authorize use of the key. See 1538 * {@link KeyProperties}.{@code AUTH} flags. 1539 * 1540 * @see #setUserAuthenticationRequired(boolean) 1541 * @see BiometricPrompt 1542 * @see BiometricPrompt.CryptoObject 1543 * @see KeyguardManager 1544 */ 1545 @NonNull setUserAuthenticationParameters(@ntRangefrom = 0) int timeout, @KeyProperties.AuthEnum int type)1546 public Builder setUserAuthenticationParameters(@IntRange(from = 0) int timeout, 1547 @KeyProperties.AuthEnum int type) { 1548 if (timeout < 0) { 1549 throw new IllegalArgumentException("timeout must be 0 or larger"); 1550 } 1551 mUserAuthenticationValidityDurationSeconds = timeout; 1552 mUserAuthenticationType = type; 1553 return this; 1554 } 1555 1556 /** 1557 * Sets whether a test of user presence is required to be performed between the 1558 * {@code Signature.initSign()} and {@code Signature.sign()} method calls. 1559 * It requires that the KeyStore implementation have a direct way to validate the user 1560 * presence for example a KeyStore hardware backed strongbox can use a button press that 1561 * is observable in hardware. A test for user presence is tangential to authentication. The 1562 * test can be part of an authentication step as long as this step can be validated by the 1563 * hardware protecting the key and cannot be spoofed. For example, a physical button press 1564 * can be used as a test of user presence if the other pins connected to the button are not 1565 * able to simulate a button press.There must be no way for the primary processor to fake a 1566 * button press, or that button must not be used as a test of user presence. 1567 */ 1568 @NonNull setUserPresenceRequired(boolean required)1569 public Builder setUserPresenceRequired(boolean required) { 1570 mUserPresenceRequired = required; 1571 return this; 1572 } 1573 1574 /** 1575 * Sets whether an attestation certificate will be generated for this key pair, and what 1576 * challenge value will be placed in the certificate. The attestation certificate chain 1577 * can be retrieved with with {@link java.security.KeyStore#getCertificateChain(String)}. 1578 * 1579 * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for 1580 * this key pair will contain an extension that describes the details of the key's 1581 * configuration and authorizations, including the {@code attestationChallenge} value. If 1582 * the key is in secure hardware, and if the secure hardware supports attestation, the 1583 * certificate will be signed by a chain of certificates rooted at a trustworthy CA key. 1584 * Otherwise the chain will be rooted at an untrusted certificate. 1585 * 1586 * <p>The purpose of the challenge value is to enable relying parties to verify that the key 1587 * was created in response to a specific request. If attestation is desired but no 1588 * challenged is needed, any non-{@code null} value may be used, including an empty byte 1589 * array. 1590 * 1591 * <p>If {@code attestationChallenge} is {@code null}, and this spec is used to generate an 1592 * asymmetric (RSA or EC) key pair, the public key certificate will be self-signed if the 1593 * key has purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}. If the key 1594 * does not have purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}, it is 1595 * not possible to use the key to sign a certificate, so the public key certificate will 1596 * contain a placeholder signature. 1597 * 1598 * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a 1599 * {@link #getAttestationChallenge()} returns non-null and the spec is used to generate a 1600 * symmetric (AES or HMAC) key, {@link javax.crypto.KeyGenerator#generateKey()} will throw 1601 * {@link java.security.InvalidAlgorithmParameterException}. 1602 * 1603 * <p>The challenge may be up to 128 bytes. 1604 */ 1605 @NonNull setAttestationChallenge(byte[] attestationChallenge)1606 public Builder setAttestationChallenge(byte[] attestationChallenge) { 1607 mAttestationChallenge = attestationChallenge; 1608 return this; 1609 } 1610 1611 /** 1612 * Sets whether to include the base device properties in the attestation certificate. 1613 * 1614 * <p>If {@code attestationChallenge} is not {@code null}, the public key certificate for 1615 * this key pair will contain an extension that describes the details of the key's 1616 * configuration and authorizations, including the device properties values (brand, device, 1617 * manufacturer, model, product). These should be the same as in ({@link Build#BRAND}, 1618 * {@link Build#DEVICE}, {@link Build#MANUFACTURER}, {@link Build#MODEL}, 1619 * {@link Build#PRODUCT}). The attestation certificate chain can 1620 * be retrieved with {@link java.security.KeyStore#getCertificateChain(String)}. 1621 * 1622 * <p> If {@code attestationChallenge} is {@code null}, the public key certificate for 1623 * this key pair will not contain the extension with the requested attested values. 1624 * 1625 * <p> {@link javax.crypto.KeyGenerator#generateKey()} will throw 1626 * {@link java.security.ProviderException} if device properties attestation fails or is not 1627 * supported. 1628 */ 1629 @NonNull setDevicePropertiesAttestationIncluded( boolean devicePropertiesAttestationIncluded)1630 public Builder setDevicePropertiesAttestationIncluded( 1631 boolean devicePropertiesAttestationIncluded) { 1632 mDevicePropertiesAttestationIncluded = devicePropertiesAttestationIncluded; 1633 return this; 1634 } 1635 1636 /** 1637 * @hide 1638 * Sets which IDs to attest in the attestation certificate for the key. The acceptable 1639 * values in this integer array are the enums specified in 1640 * {@link android.security.keystore.AttestationUtils} 1641 * 1642 * @param attestationIds the array of ID types to attest to in the certificate. 1643 * 1644 * @see android.security.keystore.AttestationUtils#ID_TYPE_SERIAL 1645 * @see android.security.keystore.AttestationUtils#ID_TYPE_IMEI 1646 * @see android.security.keystore.AttestationUtils#ID_TYPE_MEID 1647 * @see android.security.keystore.AttestationUtils#USE_INDIVIDUAL_ATTESTATION 1648 */ 1649 @SystemApi 1650 @NonNull setAttestationIds(@onNull int[] attestationIds)1651 public Builder setAttestationIds(@NonNull int[] attestationIds) { 1652 mAttestationIds = attestationIds; 1653 return this; 1654 } 1655 1656 /** 1657 * @hide Only system apps can use this method. 1658 * 1659 * Sets whether to include a temporary unique ID field in the attestation certificate. 1660 */ 1661 @UnsupportedAppUsage 1662 @TestApi 1663 @NonNull setUniqueIdIncluded(boolean uniqueIdIncluded)1664 public Builder setUniqueIdIncluded(boolean uniqueIdIncluded) { 1665 mUniqueIdIncluded = uniqueIdIncluded; 1666 return this; 1667 } 1668 1669 /** 1670 * Sets whether the key will remain authorized only until the device is removed from the 1671 * user's body up to the limit of the authentication validity period (see 1672 * {@link #setUserAuthenticationValidityDurationSeconds} and 1673 * {@link #setUserAuthenticationRequired}). Once the device has been removed from the 1674 * user's body, the key will be considered unauthorized and the user will need to 1675 * re-authenticate to use it. If the device does not have an on-body sensor or the key does 1676 * not have an authentication validity period, this parameter has no effect. 1677 * <p> 1678 * Since Android 12 (API level 31), this parameter has no effect even on devices that have 1679 * an on-body sensor. A future version of Android may restore enforcement of this parameter. 1680 * Meanwhile, it is recommended to not use it. 1681 * 1682 * @param remainsValid if {@code true}, and if the device supports enforcement of this 1683 * parameter, the key will be invalidated when the device is removed from the user's body or 1684 * when the authentication validity expires, whichever occurs first. 1685 */ 1686 @NonNull setUserAuthenticationValidWhileOnBody(boolean remainsValid)1687 public Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid) { 1688 mUserAuthenticationValidWhileOnBody = remainsValid; 1689 return this; 1690 } 1691 1692 /** 1693 * Sets whether this key should be invalidated on biometric enrollment. This 1694 * applies only to keys which require user authentication (see {@link 1695 * #setUserAuthenticationRequired(boolean)}) and if no positive validity duration has been 1696 * set (see {@link #setUserAuthenticationValidityDurationSeconds(int)}, meaning the key is 1697 * valid for biometric authentication only. 1698 * 1699 * <p>By default, {@code invalidateKey} is {@code true}, so keys that are valid for 1700 * biometric authentication only are <em>irreversibly invalidated</em> when a new 1701 * biometric is enrolled, or when all existing biometrics are deleted. That may be 1702 * changed by calling this method with {@code invalidateKey} set to {@code false}. 1703 * 1704 * <p>Invalidating keys on enrollment of a new biometric or unenrollment of all biometrics 1705 * improves security by ensuring that an unauthorized person who obtains the password can't 1706 * gain the use of biometric-authenticated keys by enrolling their own biometric. However, 1707 * invalidating keys makes key-dependent operations impossible, requiring some fallback 1708 * procedure to authenticate the user and set up a new key. 1709 */ 1710 @NonNull setInvalidatedByBiometricEnrollment(boolean invalidateKey)1711 public Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey) { 1712 mInvalidatedByBiometricEnrollment = invalidateKey; 1713 return this; 1714 } 1715 1716 /** 1717 * Sets whether this key should be protected by a StrongBox security chip. 1718 */ 1719 @NonNull setIsStrongBoxBacked(boolean isStrongBoxBacked)1720 public Builder setIsStrongBoxBacked(boolean isStrongBoxBacked) { 1721 mIsStrongBoxBacked = isStrongBoxBacked; 1722 return this; 1723 } 1724 1725 /** 1726 * Sets whether this key is authorized to be used only while the device is unlocked. 1727 * <p> 1728 * The device is considered to be locked for a user when the user's apps are currently 1729 * inaccessible and some form of lock screen authentication is required to regain access to 1730 * them. For the full definition, see {@link KeyguardManager#isDeviceLocked()}. 1731 * <p> 1732 * Public key operations aren't restricted by {@code setUnlockedDeviceRequired(true)} and 1733 * may be performed even while the device is locked. In Android 11 (API level 30) and lower, 1734 * encryption and verification operations with symmetric keys weren't restricted either. 1735 * <p> 1736 * Keys that use {@code setUnlockedDeviceRequired(true)} can be imported and generated even 1737 * while the device is locked, as long as the device has been unlocked at least once since 1738 * the last reboot. However, such keys cannot be used (except for the unrestricted 1739 * operations mentioned above) until the device is unlocked. Apps that need to encrypt data 1740 * while the device is locked such that it can only be decrypted while the device is 1741 * unlocked can generate a key and encrypt the data in software, import the key into 1742 * Keystore using {@code setUnlockedDeviceRequired(true)}, and zeroize the original key. 1743 * <p> 1744 * {@code setUnlockedDeviceRequired(true)} is related to but distinct from 1745 * {@link #setUserAuthenticationRequired(boolean) setUserAuthenticationRequired(true)}. 1746 * {@code setUnlockedDeviceRequired(true)} requires that the device be unlocked, whereas 1747 * {@code setUserAuthenticationRequired(true)} requires that a specific type of strong 1748 * authentication has happened within a specific time period. They may be used together or 1749 * separately; there are cases in which one requirement can be satisfied but not the other. 1750 * <p> 1751 * <b>Warning:</b> Be careful using {@code setUnlockedDeviceRequired(true)} on Android 14 1752 * (API level 34) and lower, since the following bugs existed in Android 12 through 14: 1753 * <ul> 1754 * <li>When the user didn't have a secure lock screen, unlocked-device-required keys 1755 * couldn't be generated, imported, or used.</li> 1756 * <li>When the user's secure lock screen was removed, all of that user's 1757 * unlocked-device-required keys were automatically deleted.</li> 1758 * <li>Unlocking the device with a non-strong biometric, such as face on many devices, 1759 * didn't re-authorize the use of unlocked-device-required keys.</li> 1760 * <li>Unlocking the device with a biometric didn't re-authorize the use of 1761 * unlocked-device-required keys in profiles that share their parent user's lock.</li> 1762 * </ul> 1763 * These issues are fixed in Android 15, so apps can avoid them by using 1764 * {@code setUnlockedDeviceRequired(true)} only on Android 15 and higher. 1765 * Apps that use both {@code setUnlockedDeviceRequired(true)} and 1766 * {@link #setUserAuthenticationRequired(boolean) setUserAuthenticationRequired(true)} 1767 * are unaffected by the first two issues, since the first two issues describe expected 1768 * behavior for {@code setUserAuthenticationRequired(true)}. 1769 */ 1770 @NonNull setUnlockedDeviceRequired(boolean unlockedDeviceRequired)1771 public Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired) { 1772 mUnlockedDeviceRequired = unlockedDeviceRequired; 1773 return this; 1774 } 1775 1776 /** 1777 * Set whether this key is critical to the device encryption flow 1778 * 1779 * This is a special flag only available to system servers to indicate the current key 1780 * is part of the device encryption flow. Setting this flag causes the key to not 1781 * be cryptographically bound to the LSKF even if the key is otherwise authentication 1782 * bound. 1783 * 1784 * @hide 1785 */ setCriticalToDeviceEncryption(boolean critical)1786 public Builder setCriticalToDeviceEncryption(boolean critical) { 1787 mCriticalToDeviceEncryption = critical; 1788 return this; 1789 } 1790 1791 /** 1792 * Sets the maximum number of times the key is allowed to be used. After every use of the 1793 * key, the use counter will decrease. This authorization applies only to secret key and 1794 * private key operations. Public key operations are not restricted. For example, after 1795 * successfully encrypting and decrypting data using methods such as 1796 * {@link Cipher#doFinal()}, the use counter of the secret key will decrease. After 1797 * successfully signing data using methods such as {@link Signature#sign()}, the use 1798 * counter of the private key will decrease. 1799 * 1800 * When the use counter is depleted, the key will be marked for deletion by Android 1801 * Keystore and any subsequent attempt to use the key will throw 1802 * {@link KeyPermanentlyInvalidatedException}. There is no key to be loaded from the 1803 * Android Keystore once the exhausted key is permanently deleted, as if the key never 1804 * existed before. 1805 * 1806 * <p>By default, there is no restriction on the usage of key. 1807 * 1808 * <p>Some secure hardware may not support this feature at all, in which case it will 1809 * be enforced in software, some secure hardware may support it but only with 1810 * maxUsageCount = 1, and some secure hardware may support it with larger value 1811 * of maxUsageCount. 1812 * 1813 * <p>The PackageManger feature flags: 1814 * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_SINGLE_USE_KEY} and 1815 * {@link android.content.pm.PackageManager#FEATURE_KEYSTORE_LIMITED_USE_KEY} can be used 1816 * to check whether the secure hardware cannot enforce this feature, can only enforce it 1817 * with maxUsageCount = 1, or can enforce it with larger value of maxUsageCount. 1818 * 1819 * @param maxUsageCount maximum number of times the key is allowed to be used or 1820 * {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there is no restriction on the 1821 * usage. 1822 */ 1823 @NonNull setMaxUsageCount(int maxUsageCount)1824 public Builder setMaxUsageCount(int maxUsageCount) { 1825 if (maxUsageCount == KeyProperties.UNRESTRICTED_USAGE_COUNT || maxUsageCount > 0) { 1826 mMaxUsageCount = maxUsageCount; 1827 return this; 1828 } 1829 throw new IllegalArgumentException("maxUsageCount is not valid"); 1830 } 1831 1832 /** 1833 * Sets the alias of the attestation key that will be used to sign the attestation 1834 * certificate for the generated key pair, if an attestation challenge is set with {@link 1835 * #setAttestationChallenge}. If an attestKeyAlias is set but no challenge, {@link 1836 * java.security.KeyPairGenerator#initialize} will throw {@link 1837 * java.security.InvalidAlgorithmParameterException}. 1838 * 1839 * <p>If the attestKeyAlias is set to null (the default), Android Keystore will select an 1840 * appropriate system-provided attestation signing key. If not null, the alias must 1841 * reference an Android Keystore Key that was created with {@link 1842 * android.security.keystore.KeyProperties#PURPOSE_ATTEST_KEY}, or key generation will throw 1843 * {@link java.security.InvalidAlgorithmParameterException}. 1844 * 1845 * @param attestKeyAlias the alias of the attestation key to be used to sign the 1846 * attestation certificate. 1847 */ 1848 @NonNull setAttestKeyAlias(@ullable String attestKeyAlias)1849 public Builder setAttestKeyAlias(@Nullable String attestKeyAlias) { 1850 mAttestKeyAlias = attestKeyAlias; 1851 return this; 1852 } 1853 1854 /** 1855 * Set the secure user id that this key should be bound to. 1856 * 1857 * Normally an authentication-bound key is tied to the secure user id of the current user 1858 * (either the root SID from GateKeeper for auth-bound keys with a timeout, or the 1859 * authenticator id of the current biometric set for keys requiring explicit biometric 1860 * authorization). If this parameter is set (this method returning non-zero value), the key 1861 * should be tied to the specified secure user id, overriding the logic above. 1862 * 1863 * This is only applicable when {@link #setUserAuthenticationRequired} is set to 1864 * {@code true} 1865 * 1866 * @see KeyGenParameterSpec#getBoundToSpecificSecureUserId() 1867 * @hide 1868 */ 1869 @NonNull setBoundToSpecificSecureUserId(long secureUserId)1870 public Builder setBoundToSpecificSecureUserId(long secureUserId) { 1871 mBoundToSecureUserId = secureUserId; 1872 return this; 1873 } 1874 1875 /** 1876 * Builds an instance of {@code KeyGenParameterSpec}. 1877 */ 1878 @NonNull build()1879 public KeyGenParameterSpec build() { 1880 return new KeyGenParameterSpec( 1881 mKeystoreAlias, 1882 mNamespace, 1883 mKeySize, 1884 mSpec, 1885 mCertificateSubject, 1886 mCertificateSerialNumber, 1887 mCertificateNotBefore, 1888 mCertificateNotAfter, 1889 mKeyValidityStart, 1890 mKeyValidityForOriginationEnd, 1891 mKeyValidityForConsumptionEnd, 1892 mPurposes, 1893 mDigests, 1894 mMgf1Digests, 1895 mEncryptionPaddings, 1896 mSignaturePaddings, 1897 mBlockModes, 1898 mRandomizedEncryptionRequired, 1899 mUserAuthenticationRequired, 1900 mUserAuthenticationValidityDurationSeconds, 1901 mUserAuthenticationType, 1902 mUserPresenceRequired, 1903 mAttestationChallenge, 1904 mDevicePropertiesAttestationIncluded, 1905 mAttestationIds, 1906 mUniqueIdIncluded, 1907 mUserAuthenticationValidWhileOnBody, 1908 mInvalidatedByBiometricEnrollment, 1909 mIsStrongBoxBacked, 1910 mUserConfirmationRequired, 1911 mUnlockedDeviceRequired, 1912 mCriticalToDeviceEncryption, 1913 mMaxUsageCount, 1914 mAttestKeyAlias, 1915 mBoundToSecureUserId); 1916 } 1917 } 1918 } 1919