AndroidKeyStoreKeyPairGeneratorSpi.java revision 856aebe571e2efe332c1258b3131bfbae6f4b396
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 17package android.security.keystore; 18 19import android.annotation.Nullable; 20import android.security.Credentials; 21import android.security.KeyPairGeneratorSpec; 22import android.security.KeyStore; 23import android.security.keymaster.KeyCharacteristics; 24import android.security.keymaster.KeymasterArguments; 25import android.security.keymaster.KeymasterDefs; 26 27import com.android.org.bouncycastle.asn1.ASN1EncodableVector; 28import com.android.org.bouncycastle.asn1.ASN1InputStream; 29import com.android.org.bouncycastle.asn1.ASN1Integer; 30import com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier; 31import com.android.org.bouncycastle.asn1.DERBitString; 32import com.android.org.bouncycastle.asn1.DERInteger; 33import com.android.org.bouncycastle.asn1.DERNull; 34import com.android.org.bouncycastle.asn1.DERSequence; 35import com.android.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; 36import com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier; 37import com.android.org.bouncycastle.asn1.x509.Certificate; 38import com.android.org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; 39import com.android.org.bouncycastle.asn1.x509.TBSCertificate; 40import com.android.org.bouncycastle.asn1.x509.Time; 41import com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator; 42import com.android.org.bouncycastle.asn1.x9.X9ObjectIdentifiers; 43import com.android.org.bouncycastle.jce.X509Principal; 44import com.android.org.bouncycastle.jce.provider.X509CertificateObject; 45import com.android.org.bouncycastle.x509.X509V3CertificateGenerator; 46 47import libcore.util.EmptyArray; 48 49import java.math.BigInteger; 50import java.security.InvalidAlgorithmParameterException; 51import java.security.KeyPair; 52import java.security.KeyPairGenerator; 53import java.security.KeyPairGeneratorSpi; 54import java.security.PrivateKey; 55import java.security.ProviderException; 56import java.security.PublicKey; 57import java.security.SecureRandom; 58import java.security.UnrecoverableKeyException; 59import java.security.cert.CertificateEncodingException; 60import java.security.cert.X509Certificate; 61import java.security.spec.AlgorithmParameterSpec; 62import java.security.spec.ECGenParameterSpec; 63import java.security.spec.RSAKeyGenParameterSpec; 64import java.util.ArrayList; 65import java.util.Collections; 66import java.util.Date; 67import java.util.HashMap; 68import java.util.HashSet; 69import java.util.List; 70import java.util.Locale; 71import java.util.Map; 72import java.util.Set; 73 74/** 75 * Provides a way to create instances of a KeyPair which will be placed in the 76 * Android keystore service usable only by the application that called it. This 77 * can be used in conjunction with 78 * {@link java.security.KeyStore#getInstance(String)} using the 79 * {@code "AndroidKeyStore"} type. 80 * <p> 81 * This class can not be directly instantiated and must instead be used via the 82 * {@link KeyPairGenerator#getInstance(String) 83 * KeyPairGenerator.getInstance("AndroidKeyStore")} API. 84 * 85 * @hide 86 */ 87public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGeneratorSpi { 88 89 public static class RSA extends AndroidKeyStoreKeyPairGeneratorSpi { 90 public RSA() { 91 super(KeymasterDefs.KM_ALGORITHM_RSA); 92 } 93 } 94 95 public static class EC extends AndroidKeyStoreKeyPairGeneratorSpi { 96 public EC() { 97 super(KeymasterDefs.KM_ALGORITHM_EC); 98 } 99 } 100 101 /* 102 * These must be kept in sync with system/security/keystore/defaults.h 103 */ 104 105 /* EC */ 106 private static final int EC_DEFAULT_KEY_SIZE = 256; 107 108 /* RSA */ 109 private static final int RSA_DEFAULT_KEY_SIZE = 2048; 110 private static final int RSA_MIN_KEY_SIZE = 512; 111 private static final int RSA_MAX_KEY_SIZE = 8192; 112 113 private static final Map<String, Integer> SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE = 114 new HashMap<String, Integer>(); 115 private static final List<String> SUPPORTED_EC_NIST_CURVE_NAMES = new ArrayList<String>(); 116 private static final List<Integer> SUPPORTED_EC_NIST_CURVE_SIZES = new ArrayList<Integer>(); 117 static { 118 // Aliases for NIST P-224 119 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-224", 224); 120 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp224r1", 224); 121 122 123 // Aliases for NIST P-256 124 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-256", 256); 125 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp256r1", 256); 126 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("prime256v1", 256); 127 128 // Aliases for NIST P-384 129 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-384", 384); 130 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp384r1", 384); 131 132 // Aliases for NIST P-521 133 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-521", 521); 134 SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp521r1", 521); 135 136 SUPPORTED_EC_NIST_CURVE_NAMES.addAll(SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.keySet()); 137 Collections.sort(SUPPORTED_EC_NIST_CURVE_NAMES); 138 139 SUPPORTED_EC_NIST_CURVE_SIZES.addAll( 140 new HashSet<Integer>(SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.values())); 141 Collections.sort(SUPPORTED_EC_NIST_CURVE_SIZES); 142 } 143 144 private final int mOriginalKeymasterAlgorithm; 145 146 private KeyStore mKeyStore; 147 148 private KeyGenParameterSpec mSpec; 149 150 private String mEntryAlias; 151 private boolean mEncryptionAtRestRequired; 152 private @KeyProperties.KeyAlgorithmEnum String mJcaKeyAlgorithm; 153 private int mKeymasterAlgorithm = -1; 154 private int mKeySizeBits; 155 private SecureRandom mRng; 156 157 private int[] mKeymasterPurposes; 158 private int[] mKeymasterBlockModes; 159 private int[] mKeymasterEncryptionPaddings; 160 private int[] mKeymasterSignaturePaddings; 161 private int[] mKeymasterDigests; 162 163 private long mRSAPublicExponent; 164 165 protected AndroidKeyStoreKeyPairGeneratorSpi(int keymasterAlgorithm) { 166 mOriginalKeymasterAlgorithm = keymasterAlgorithm; 167 } 168 169 @Override 170 public void initialize(int keysize, SecureRandom random) { 171 throw new IllegalArgumentException( 172 KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName() 173 + " required to initialize this KeyPairGenerator"); 174 } 175 176 @Override 177 public void initialize(AlgorithmParameterSpec params, SecureRandom random) 178 throws InvalidAlgorithmParameterException { 179 resetAll(); 180 181 boolean success = false; 182 try { 183 if (params == null) { 184 throw new InvalidAlgorithmParameterException( 185 "Must supply params of type " + KeyGenParameterSpec.class.getName() 186 + " or " + KeyPairGeneratorSpec.class.getName()); 187 } 188 189 KeyGenParameterSpec spec; 190 boolean encryptionAtRestRequired = false; 191 int keymasterAlgorithm = mOriginalKeymasterAlgorithm; 192 if (params instanceof KeyGenParameterSpec) { 193 spec = (KeyGenParameterSpec) params; 194 } else if (params instanceof KeyPairGeneratorSpec) { 195 // Legacy/deprecated spec 196 KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params; 197 try { 198 KeyGenParameterSpec.Builder specBuilder; 199 String specKeyAlgorithm = legacySpec.getKeyType(); 200 if (specKeyAlgorithm != null) { 201 // Spec overrides the generator's default key algorithm 202 try { 203 keymasterAlgorithm = 204 KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm( 205 specKeyAlgorithm); 206 } catch (IllegalArgumentException e) { 207 throw new InvalidAlgorithmParameterException( 208 "Invalid key type in parameters", e); 209 } 210 } 211 switch (keymasterAlgorithm) { 212 case KeymasterDefs.KM_ALGORITHM_EC: 213 specBuilder = new KeyGenParameterSpec.Builder( 214 legacySpec.getKeystoreAlias(), 215 KeyProperties.PURPOSE_SIGN 216 | KeyProperties.PURPOSE_VERIFY); 217 // Authorized to be used with any digest (including no digest). 218 specBuilder.setDigests(KeyProperties.DIGEST_NONE); 219 break; 220 case KeymasterDefs.KM_ALGORITHM_RSA: 221 specBuilder = new KeyGenParameterSpec.Builder( 222 legacySpec.getKeystoreAlias(), 223 KeyProperties.PURPOSE_ENCRYPT 224 | KeyProperties.PURPOSE_DECRYPT 225 | KeyProperties.PURPOSE_SIGN 226 | KeyProperties.PURPOSE_VERIFY); 227 // Authorized to be used with any digest (including no digest). 228 specBuilder.setDigests(KeyProperties.DIGEST_NONE); 229 // Authorized to be used with any encryption and signature padding 230 // scheme (including no padding). 231 specBuilder.setEncryptionPaddings( 232 KeyProperties.ENCRYPTION_PADDING_NONE); 233 // Disable randomized encryption requirement to support encryption 234 // padding NONE above. 235 specBuilder.setRandomizedEncryptionRequired(false); 236 break; 237 default: 238 throw new ProviderException( 239 "Unsupported algorithm: " + mKeymasterAlgorithm); 240 } 241 242 if (legacySpec.getKeySize() != -1) { 243 specBuilder.setKeySize(legacySpec.getKeySize()); 244 } 245 if (legacySpec.getAlgorithmParameterSpec() != null) { 246 specBuilder.setAlgorithmParameterSpec( 247 legacySpec.getAlgorithmParameterSpec()); 248 } 249 specBuilder.setCertificateSubject(legacySpec.getSubjectDN()); 250 specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber()); 251 specBuilder.setCertificateNotBefore(legacySpec.getStartDate()); 252 specBuilder.setCertificateNotAfter(legacySpec.getEndDate()); 253 encryptionAtRestRequired = legacySpec.isEncryptionRequired(); 254 specBuilder.setUserAuthenticationRequired(false); 255 256 spec = specBuilder.build(); 257 } catch (NullPointerException | IllegalArgumentException e) { 258 throw new InvalidAlgorithmParameterException(e); 259 } 260 } else { 261 throw new InvalidAlgorithmParameterException( 262 "Unsupported params class: " + params.getClass().getName() 263 + ". Supported: " + KeyGenParameterSpec.class.getName() 264 + ", " + KeyPairGeneratorSpec.class.getName()); 265 } 266 267 mEntryAlias = spec.getKeystoreAlias(); 268 mSpec = spec; 269 mKeymasterAlgorithm = keymasterAlgorithm; 270 mEncryptionAtRestRequired = encryptionAtRestRequired; 271 mKeySizeBits = spec.getKeySize(); 272 initAlgorithmSpecificParameters(); 273 if (mKeySizeBits == -1) { 274 mKeySizeBits = getDefaultKeySize(keymasterAlgorithm); 275 } 276 checkValidKeySize(keymasterAlgorithm, mKeySizeBits); 277 278 if (spec.getKeystoreAlias() == null) { 279 throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided"); 280 } 281 282 String jcaKeyAlgorithm; 283 try { 284 jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm( 285 keymasterAlgorithm); 286 mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes()); 287 mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes()); 288 mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster( 289 spec.getEncryptionPaddings()); 290 mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster( 291 spec.getSignaturePaddings()); 292 if (spec.isDigestsSpecified()) { 293 mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests()); 294 } else { 295 mKeymasterDigests = EmptyArray.INT; 296 } 297 } catch (IllegalArgumentException e) { 298 throw new InvalidAlgorithmParameterException(e); 299 } 300 301 mJcaKeyAlgorithm = jcaKeyAlgorithm; 302 mRng = random; 303 mKeyStore = KeyStore.getInstance(); 304 success = true; 305 } finally { 306 if (!success) { 307 resetAll(); 308 } 309 } 310 } 311 312 private void resetAll() { 313 mEntryAlias = null; 314 mJcaKeyAlgorithm = null; 315 mKeymasterAlgorithm = -1; 316 mKeymasterPurposes = null; 317 mKeymasterBlockModes = null; 318 mKeymasterEncryptionPaddings = null; 319 mKeymasterSignaturePaddings = null; 320 mKeymasterDigests = null; 321 mKeySizeBits = 0; 322 mSpec = null; 323 mRSAPublicExponent = -1; 324 mEncryptionAtRestRequired = false; 325 mRng = null; 326 mKeyStore = null; 327 } 328 329 private void initAlgorithmSpecificParameters() throws InvalidAlgorithmParameterException { 330 AlgorithmParameterSpec algSpecificSpec = mSpec.getAlgorithmParameterSpec(); 331 switch (mKeymasterAlgorithm) { 332 case KeymasterDefs.KM_ALGORITHM_RSA: 333 { 334 BigInteger publicExponent = null; 335 if (algSpecificSpec instanceof RSAKeyGenParameterSpec) { 336 RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec) algSpecificSpec; 337 if (mKeySizeBits == -1) { 338 mKeySizeBits = rsaSpec.getKeysize(); 339 } else if (mKeySizeBits != rsaSpec.getKeysize()) { 340 throw new InvalidAlgorithmParameterException("RSA key size must match " 341 + " between " + mSpec + " and " + algSpecificSpec 342 + ": " + mKeySizeBits + " vs " + rsaSpec.getKeysize()); 343 } 344 publicExponent = rsaSpec.getPublicExponent(); 345 } else if (algSpecificSpec != null) { 346 throw new InvalidAlgorithmParameterException( 347 "RSA may only use RSAKeyGenParameterSpec"); 348 } 349 if (publicExponent == null) { 350 publicExponent = RSAKeyGenParameterSpec.F4; 351 } 352 if (publicExponent.compareTo(BigInteger.ZERO) < 1) { 353 throw new InvalidAlgorithmParameterException( 354 "RSA public exponent must be positive: " + publicExponent); 355 } 356 if (publicExponent.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { 357 throw new InvalidAlgorithmParameterException( 358 "Unsupported RSA public exponent: " + publicExponent 359 + ". Only exponents <= " + Long.MAX_VALUE + " supported"); 360 } 361 mRSAPublicExponent = publicExponent.longValue(); 362 break; 363 } 364 case KeymasterDefs.KM_ALGORITHM_EC: 365 if (algSpecificSpec instanceof ECGenParameterSpec) { 366 ECGenParameterSpec ecSpec = (ECGenParameterSpec) algSpecificSpec; 367 String curveName = ecSpec.getName(); 368 Integer ecSpecKeySizeBits = SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.get( 369 curveName.toLowerCase(Locale.US)); 370 if (ecSpecKeySizeBits == null) { 371 throw new InvalidAlgorithmParameterException( 372 "Unsupported EC curve name: " + curveName 373 + ". Supported: " + SUPPORTED_EC_NIST_CURVE_NAMES); 374 } 375 if (mKeySizeBits == -1) { 376 mKeySizeBits = ecSpecKeySizeBits; 377 } else if (mKeySizeBits != ecSpecKeySizeBits) { 378 throw new InvalidAlgorithmParameterException("EC key size must match " 379 + " between " + mSpec + " and " + algSpecificSpec 380 + ": " + mKeySizeBits + " vs " + ecSpecKeySizeBits); 381 } 382 } else if (algSpecificSpec != null) { 383 throw new InvalidAlgorithmParameterException( 384 "EC may only use ECGenParameterSpec"); 385 } 386 break; 387 default: 388 throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm); 389 } 390 } 391 392 @Override 393 public KeyPair generateKeyPair() { 394 if (mKeyStore == null || mSpec == null) { 395 throw new IllegalStateException("Not initialized"); 396 } 397 398 final int flags = (mEncryptionAtRestRequired) ? KeyStore.FLAG_ENCRYPTED : 0; 399 if (((flags & KeyStore.FLAG_ENCRYPTED) != 0) 400 && (mKeyStore.state() != KeyStore.State.UNLOCKED)) { 401 throw new IllegalStateException( 402 "Encryption at rest using secure lock screen credential requested for key pair" 403 + ", but the user has not yet entered the credential"); 404 } 405 406 KeymasterArguments args = new KeymasterArguments(); 407 args.addInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits); 408 args.addInt(KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm); 409 args.addInts(KeymasterDefs.KM_TAG_PURPOSE, mKeymasterPurposes); 410 args.addInts(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockModes); 411 args.addInts(KeymasterDefs.KM_TAG_PADDING, mKeymasterEncryptionPaddings); 412 args.addInts(KeymasterDefs.KM_TAG_PADDING, mKeymasterSignaturePaddings); 413 args.addInts(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigests); 414 415 KeymasterUtils.addUserAuthArgs(args, 416 mSpec.isUserAuthenticationRequired(), 417 mSpec.getUserAuthenticationValidityDurationSeconds()); 418 args.addDate(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, 419 (mSpec.getKeyValidityStart() != null) 420 ? mSpec.getKeyValidityStart() : new Date(0)); 421 args.addDate(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, 422 (mSpec.getKeyValidityForOriginationEnd() != null) 423 ? mSpec.getKeyValidityForOriginationEnd() : new Date(Long.MAX_VALUE)); 424 args.addDate(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, 425 (mSpec.getKeyValidityForConsumptionEnd() != null) 426 ? mSpec.getKeyValidityForConsumptionEnd() : new Date(Long.MAX_VALUE)); 427 addAlgorithmSpecificParameters(args); 428 429 byte[] additionalEntropy = 430 KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng( 431 mRng, (mKeySizeBits + 7) / 8); 432 433 final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + mEntryAlias; 434 boolean success = false; 435 try { 436 Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias); 437 KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics(); 438 int errorCode = mKeyStore.generateKey( 439 privateKeyAlias, 440 args, 441 additionalEntropy, 442 flags, 443 resultingKeyCharacteristics); 444 if (errorCode != KeyStore.NO_ERROR) { 445 throw new ProviderException( 446 "Failed to generate key pair", KeyStore.getKeyStoreException(errorCode)); 447 } 448 449 KeyPair result; 450 try { 451 result = AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore( 452 mKeyStore, privateKeyAlias); 453 } catch (UnrecoverableKeyException e) { 454 throw new ProviderException("Failed to load generated key pair from keystore", e); 455 } 456 457 if (!mJcaKeyAlgorithm.equalsIgnoreCase(result.getPrivate().getAlgorithm())) { 458 throw new ProviderException( 459 "Generated key pair algorithm does not match requested algorithm: " 460 + result.getPrivate().getAlgorithm() + " vs " + mJcaKeyAlgorithm); 461 } 462 463 final X509Certificate cert; 464 try { 465 cert = generateSelfSignedCertificate(result.getPrivate(), result.getPublic()); 466 } catch (Exception e) { 467 throw new ProviderException("Failed to generate self-signed certificate", e); 468 } 469 470 byte[] certBytes; 471 try { 472 certBytes = cert.getEncoded(); 473 } catch (CertificateEncodingException e) { 474 throw new ProviderException( 475 "Failed to obtain encoded form of self-signed certificate", e); 476 } 477 478 int insertErrorCode = mKeyStore.insert( 479 Credentials.USER_CERTIFICATE + mEntryAlias, 480 certBytes, 481 KeyStore.UID_SELF, 482 flags); 483 if (insertErrorCode != KeyStore.NO_ERROR) { 484 throw new ProviderException("Failed to store self-signed certificate", 485 KeyStore.getKeyStoreException(insertErrorCode)); 486 } 487 488 success = true; 489 return result; 490 } finally { 491 if (!success) { 492 Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias); 493 } 494 } 495 } 496 497 private void addAlgorithmSpecificParameters(KeymasterArguments keymasterArgs) { 498 switch (mKeymasterAlgorithm) { 499 case KeymasterDefs.KM_ALGORITHM_RSA: 500 keymasterArgs.addLong(KeymasterDefs.KM_TAG_RSA_PUBLIC_EXPONENT, mRSAPublicExponent); 501 break; 502 case KeymasterDefs.KM_ALGORITHM_EC: 503 break; 504 default: 505 throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm); 506 } 507 } 508 509 private X509Certificate generateSelfSignedCertificate( 510 PrivateKey privateKey, PublicKey publicKey) throws Exception { 511 String signatureAlgorithm = 512 getCertificateSignatureAlgorithm(mKeymasterAlgorithm, mKeySizeBits, mSpec); 513 if (signatureAlgorithm == null) { 514 // Key cannot be used to sign a certificate 515 return generateSelfSignedCertificateWithFakeSignature(publicKey); 516 } else { 517 // Key can be used to sign a certificate 518 try { 519 return generateSelfSignedCertificateWithValidSignature( 520 privateKey, publicKey, signatureAlgorithm); 521 } catch (Exception e) { 522 // Failed to generate the self-signed certificate with valid signature. Fall back 523 // to generating a self-signed certificate with a fake signature. This is done for 524 // all exception types because we prefer key pair generation to succeed and end up 525 // producing a self-signed certificate with an invalid signature to key pair 526 // generation failing. 527 return generateSelfSignedCertificateWithFakeSignature(publicKey); 528 } 529 } 530 } 531 532 @SuppressWarnings("deprecation") 533 private X509Certificate generateSelfSignedCertificateWithValidSignature( 534 PrivateKey privateKey, PublicKey publicKey, String signatureAlgorithm) throws Exception { 535 final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); 536 certGen.setPublicKey(publicKey); 537 certGen.setSerialNumber(mSpec.getCertificateSerialNumber()); 538 certGen.setSubjectDN(mSpec.getCertificateSubject()); 539 certGen.setIssuerDN(mSpec.getCertificateSubject()); 540 certGen.setNotBefore(mSpec.getCertificateNotBefore()); 541 certGen.setNotAfter(mSpec.getCertificateNotAfter()); 542 certGen.setSignatureAlgorithm(signatureAlgorithm); 543 return certGen.generate(privateKey); 544 } 545 546 @SuppressWarnings("deprecation") 547 private X509Certificate generateSelfSignedCertificateWithFakeSignature( 548 PublicKey publicKey) throws Exception { 549 V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator(); 550 ASN1ObjectIdentifier sigAlgOid; 551 AlgorithmIdentifier sigAlgId; 552 byte[] signature; 553 switch (mKeymasterAlgorithm) { 554 case KeymasterDefs.KM_ALGORITHM_EC: 555 sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256; 556 sigAlgId = new AlgorithmIdentifier(sigAlgOid); 557 ASN1EncodableVector v = new ASN1EncodableVector(); 558 v.add(new DERInteger(0)); 559 v.add(new DERInteger(0)); 560 signature = new DERSequence().getEncoded(); 561 break; 562 case KeymasterDefs.KM_ALGORITHM_RSA: 563 sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption; 564 sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE); 565 signature = new byte[1]; 566 break; 567 default: 568 throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm); 569 } 570 571 try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) { 572 tbsGenerator.setSubjectPublicKeyInfo( 573 SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject())); 574 } 575 tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber())); 576 X509Principal subject = 577 new X509Principal(mSpec.getCertificateSubject().getEncoded()); 578 tbsGenerator.setSubject(subject); 579 tbsGenerator.setIssuer(subject); 580 tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore())); 581 tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter())); 582 tbsGenerator.setSignature(sigAlgId); 583 TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate(); 584 585 ASN1EncodableVector result = new ASN1EncodableVector(); 586 result.add(tbsCertificate); 587 result.add(sigAlgId); 588 result.add(new DERBitString(signature)); 589 return new X509CertificateObject(Certificate.getInstance(new DERSequence(result))); 590 } 591 592 private static int getDefaultKeySize(int keymasterAlgorithm) { 593 switch (keymasterAlgorithm) { 594 case KeymasterDefs.KM_ALGORITHM_EC: 595 return EC_DEFAULT_KEY_SIZE; 596 case KeymasterDefs.KM_ALGORITHM_RSA: 597 return RSA_DEFAULT_KEY_SIZE; 598 default: 599 throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); 600 } 601 } 602 603 private static void checkValidKeySize(int keymasterAlgorithm, int keySize) 604 throws InvalidAlgorithmParameterException { 605 switch (keymasterAlgorithm) { 606 case KeymasterDefs.KM_ALGORITHM_EC: 607 if (!SUPPORTED_EC_NIST_CURVE_SIZES.contains(keySize)) { 608 throw new InvalidAlgorithmParameterException("Unsupported EC key size: " 609 + keySize + " bits. Supported: " + SUPPORTED_EC_NIST_CURVE_SIZES); 610 } 611 break; 612 case KeymasterDefs.KM_ALGORITHM_RSA: 613 if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) { 614 throw new InvalidAlgorithmParameterException("RSA key size must be >= " 615 + RSA_MIN_KEY_SIZE + " and <= " + RSA_MAX_KEY_SIZE); 616 } 617 break; 618 default: 619 throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); 620 } 621 } 622 623 /** 624 * Returns the {@code Signature} algorithm to be used for signing a certificate using the 625 * specified key or {@code null} if the key cannot be used for signing a certificate. 626 */ 627 @Nullable 628 private static String getCertificateSignatureAlgorithm( 629 int keymasterAlgorithm, 630 int keySizeBits, 631 KeyGenParameterSpec spec) { 632 // Constraints: 633 // 1. Key must be authorized for signing without user authentication. 634 // 2. Signature digest must be one of key's authorized digests. 635 // 3. For RSA keys, the digest output size must not exceed modulus size minus space overhead 636 // of RSA PKCS#1 signature padding scheme (about 30 bytes). 637 // 4. For EC keys, the there is no point in using a digest whose output size is longer than 638 // key/field size because the digest will be truncated to that size. 639 640 if ((spec.getPurposes() & KeyProperties.PURPOSE_SIGN) == 0) { 641 // Key not authorized for signing 642 return null; 643 } 644 if (spec.isUserAuthenticationRequired()) { 645 // Key not authorized for use without user authentication 646 return null; 647 } 648 if (!spec.isDigestsSpecified()) { 649 // Key not authorized for any digests -- can't sign 650 return null; 651 } 652 switch (keymasterAlgorithm) { 653 case KeymasterDefs.KM_ALGORITHM_EC: 654 { 655 Set<Integer> availableKeymasterDigests = getAvailableKeymasterSignatureDigests( 656 spec.getDigests(), 657 AndroidKeyStoreBCWorkaroundProvider.getSupportedEcdsaSignatureDigests()); 658 659 int bestKeymasterDigest = -1; 660 int bestDigestOutputSizeBits = -1; 661 for (int keymasterDigest : availableKeymasterDigests) { 662 int outputSizeBits = KeymasterUtils.getDigestOutputSizeBits(keymasterDigest); 663 if (outputSizeBits == keySizeBits) { 664 // Perfect match -- use this digest 665 bestKeymasterDigest = keymasterDigest; 666 bestDigestOutputSizeBits = outputSizeBits; 667 break; 668 } 669 // Not a perfect match -- check against the best digest so far 670 if (bestKeymasterDigest == -1) { 671 // First digest tested -- definitely the best so far 672 bestKeymasterDigest = keymasterDigest; 673 bestDigestOutputSizeBits = outputSizeBits; 674 } else { 675 // Prefer output size to be as close to key size as possible, with output 676 // sizes larger than key size preferred to those smaller than key size. 677 if (bestDigestOutputSizeBits < keySizeBits) { 678 // Output size of the best digest so far is smaller than key size. 679 // Anything larger is a win. 680 if (outputSizeBits > bestDigestOutputSizeBits) { 681 bestKeymasterDigest = keymasterDigest; 682 bestDigestOutputSizeBits = outputSizeBits; 683 } 684 } else { 685 // Output size of the best digest so far is larger than key size. 686 // Anything smaller is a win, as long as it's not smaller than key size. 687 if ((outputSizeBits < bestDigestOutputSizeBits) 688 && (outputSizeBits >= keySizeBits)) { 689 bestKeymasterDigest = keymasterDigest; 690 bestDigestOutputSizeBits = outputSizeBits; 691 } 692 } 693 } 694 } 695 if (bestKeymasterDigest == -1) { 696 return null; 697 } 698 return KeyProperties.Digest.fromKeymasterToSignatureAlgorithmDigest( 699 bestKeymasterDigest) + "WithECDSA"; 700 } 701 case KeymasterDefs.KM_ALGORITHM_RSA: 702 { 703 // Check whether this key is authorized for PKCS#1 signature padding. 704 // We use Bouncy Castle to generate self-signed RSA certificates. Bouncy Castle 705 // only supports RSA certificates signed using PKCS#1 padding scheme. The key needs 706 // to be authorized for PKCS#1 padding or padding NONE which means any padding. 707 boolean pkcs1SignaturePaddingSupported = false; 708 for (int keymasterPadding : KeyProperties.SignaturePadding.allToKeymaster( 709 spec.getSignaturePaddings())) { 710 if ((keymasterPadding == KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN) 711 || (keymasterPadding == KeymasterDefs.KM_PAD_NONE)) { 712 pkcs1SignaturePaddingSupported = true; 713 break; 714 } 715 } 716 if (!pkcs1SignaturePaddingSupported) { 717 // Keymaster doesn't distinguish between encryption padding NONE and signature 718 // padding NONE. In the Android Keystore API only encryption padding NONE is 719 // exposed. 720 for (int keymasterPadding : KeyProperties.EncryptionPadding.allToKeymaster( 721 spec.getEncryptionPaddings())) { 722 if (keymasterPadding == KeymasterDefs.KM_PAD_NONE) { 723 pkcs1SignaturePaddingSupported = true; 724 break; 725 } 726 } 727 } 728 if (!pkcs1SignaturePaddingSupported) { 729 // Key not authorized for PKCS#1 signature padding -- can't sign 730 return null; 731 } 732 733 Set<Integer> availableKeymasterDigests = getAvailableKeymasterSignatureDigests( 734 spec.getDigests(), 735 AndroidKeyStoreBCWorkaroundProvider.getSupportedEcdsaSignatureDigests()); 736 737 // The amount of space available for the digest is less than modulus size by about 738 // 30 bytes because padding must be at least 11 bytes long (00 || 01 || PS || 00, 739 // where PS must be at least 8 bytes long), and then there's also the 15--19 bytes 740 // overhead (depending the on chosen digest) for encoding digest OID and digest 741 // value in DER. 742 int maxDigestOutputSizeBits = keySizeBits - 30 * 8; 743 int bestKeymasterDigest = -1; 744 int bestDigestOutputSizeBits = -1; 745 for (int keymasterDigest : availableKeymasterDigests) { 746 int outputSizeBits = KeymasterUtils.getDigestOutputSizeBits(keymasterDigest); 747 if (outputSizeBits > maxDigestOutputSizeBits) { 748 // Digest too long (signature generation will fail) -- skip 749 continue; 750 } 751 if (bestKeymasterDigest == -1) { 752 // First digest tested -- definitely the best so far 753 bestKeymasterDigest = keymasterDigest; 754 bestDigestOutputSizeBits = outputSizeBits; 755 } else { 756 // The longer the better 757 if (outputSizeBits > bestDigestOutputSizeBits) { 758 bestKeymasterDigest = keymasterDigest; 759 bestDigestOutputSizeBits = outputSizeBits; 760 } 761 } 762 } 763 if (bestKeymasterDigest == -1) { 764 return null; 765 } 766 return KeyProperties.Digest.fromKeymasterToSignatureAlgorithmDigest( 767 bestKeymasterDigest) + "WithRSA"; 768 } 769 default: 770 throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); 771 } 772 } 773 774 private static Set<Integer> getAvailableKeymasterSignatureDigests( 775 @KeyProperties.DigestEnum String[] authorizedKeyDigests, 776 @KeyProperties.DigestEnum String[] supportedSignatureDigests) { 777 Set<Integer> authorizedKeymasterKeyDigests = new HashSet<Integer>(); 778 for (int keymasterDigest : KeyProperties.Digest.allToKeymaster(authorizedKeyDigests)) { 779 authorizedKeymasterKeyDigests.add(keymasterDigest); 780 } 781 Set<Integer> supportedKeymasterSignatureDigests = new HashSet<Integer>(); 782 for (int keymasterDigest 783 : KeyProperties.Digest.allToKeymaster(supportedSignatureDigests)) { 784 supportedKeymasterSignatureDigests.add(keymasterDigest); 785 } 786 if (authorizedKeymasterKeyDigests.contains(KeymasterDefs.KM_DIGEST_NONE)) { 787 // Key is authorized to be used with any digest 788 return supportedKeymasterSignatureDigests; 789 } else { 790 // Key is authorized to be used only with specific digests. 791 Set<Integer> result = new HashSet<Integer>(supportedKeymasterSignatureDigests); 792 result.retainAll(authorizedKeymasterKeyDigests); 793 return result; 794 } 795 } 796} 797