Debian Codegraph @

keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java

raw symbols SCIP
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.keystore2;
18
19 import static android.security.keystore2.AndroidKeyStoreCipherSpiBase.DEFAULT_MGF1_DIGEST;
20
21 import android.annotation.NonNull;
22 import android.hardware.biometrics.BiometricManager;
23 import android.hardware.security.keymint.EcCurve;
24 import android.hardware.security.keymint.HardwareAuthenticatorType;
25 import android.hardware.security.keymint.KeyParameter;
26 import android.hardware.security.keymint.SecurityLevel;
27 import android.security.GateKeeper;
28 import android.security.KeyStore2;
29 import android.security.KeyStoreParameter;
30 import android.security.KeyStoreSecurityLevel;
31 import android.security.keymaster.KeymasterDefs;
32 import android.security.keystore.KeyGenParameterSpec;
33 import android.security.keystore.KeyPermanentlyInvalidatedException;
34 import android.security.keystore.KeyProperties;
35 import android.security.keystore.KeyProtection;
36 import android.security.keystore.SecureKeyImportUnavailableException;
37 import android.security.keystore.WrappedKeyEntry;
38 import android.system.keystore2.AuthenticatorSpec;
39 import android.system.keystore2.Domain;
40 import android.system.keystore2.IKeystoreSecurityLevel;
41 import android.system.keystore2.KeyDescriptor;
42 import android.system.keystore2.KeyEntryResponse;
43 import android.system.keystore2.KeyMetadata;
44 import android.system.keystore2.ResponseCode;
45 import android.util.Log;
46
47 import com.android.internal.annotations.VisibleForTesting;
48
49 import java.io.ByteArrayInputStream;
50 import java.io.IOException;
51 import java.io.InputStream;
52 import java.io.OutputStream;
53 import java.security.Key;
54 import java.security.KeyStore.Entry;
55 import java.security.KeyStore.LoadStoreParameter;
56 import java.security.KeyStore.PrivateKeyEntry;
57 import java.security.KeyStore.ProtectionParameter;
58 import java.security.KeyStore.SecretKeyEntry;
59 import java.security.KeyStoreException;
60 import java.security.KeyStoreSpi;
61 import java.security.NoSuchAlgorithmException;
62 import java.security.PrivateKey;
63 import java.security.ProviderException;
64 import java.security.UnrecoverableKeyException;
65 import java.security.cert.Certificate;
66 import java.security.cert.CertificateEncodingException;
67 import java.security.cert.CertificateException;
68 import java.security.cert.CertificateFactory;
69 import java.security.cert.X509Certificate;
70 import java.security.interfaces.ECKey;
71 import java.security.interfaces.ECPrivateKey;
72 import java.security.interfaces.EdECKey;
73 import java.security.interfaces.EdECPrivateKey;
74 import java.security.interfaces.XECKey;
75 import java.security.interfaces.XECPrivateKey;
76 import java.security.spec.AlgorithmParameterSpec;
77 import java.security.spec.ECParameterSpec;
78 import java.security.spec.NamedParameterSpec;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.Collection;
82 import java.util.Date;
83 import java.util.Enumeration;
84 import java.util.Iterator;
85 import java.util.List;
86 import java.util.NoSuchElementException;
87
88 import javax.crypto.SecretKey;
89
90 /**
91 * A java.security.KeyStore interface for the Android KeyStore. An instance of
92 * it can be created via the {@link java.security.KeyStore#getInstance(String)
93 * KeyStore.getInstance("AndroidKeyStore")} interface. This returns a
94 * java.security.KeyStore backed by this "AndroidKeyStore" implementation.
95 * <p>
96 * This is built on top of Android's keystore daemon. The convention of alias
97 * use is:
98 * <p>
99 * PrivateKeyEntry will have a Credentials.USER_PRIVATE_KEY as the private key,
100 * Credentials.USER_CERTIFICATE as the first certificate in the chain (the one
101 * that corresponds to the private key), and then a Credentials.CA_CERTIFICATE
102 * entry which will have the rest of the chain concatenated in BER format.
103 * <p>
104 * TrustedCertificateEntry will just have a Credentials.CA_CERTIFICATE entry
105 * with a single certificate.
106 *
107 * @hide
108 */
109 public class AndroidKeyStoreSpi extends KeyStoreSpi {
110 public static final String TAG = "AndroidKeyStoreSpi";
111 public static final String NAME = "AndroidKeyStore";
112
113 private KeyStore2 mKeyStore;
114 private @KeyProperties.Namespace int mNamespace = KeyProperties.NAMESPACE_APPLICATION;
115
116 @Override
117 public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException,
118 UnrecoverableKeyException {
119 try {
120 return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore(mKeyStore,
121 alias,
122 mNamespace);
123 } catch (KeyPermanentlyInvalidatedException e) {
124 throw new UnrecoverableKeyException(e.getMessage());
125 } catch (UnrecoverableKeyException e) {
126 Throwable cause = e.getCause();
127 if (cause instanceof android.security.KeyStoreException) {
128 if (((android.security.KeyStoreException) cause).getErrorCode()
129 == ResponseCode.KEY_NOT_FOUND) {
130 return null;
131 }
132 }
133 throw e;
134 }
135 }
136
137 /**
138 * Make a key descriptor from the given alias and the mNamespace member.
139 * If mNamespace is -1 it sets the domain field to {@link Domain#APP} and {@link Domain#SELINUX}
140 * otherwise. The blob field is always set to null and the alias field to {@code alias}
141 * @param alias The alias of the new key descriptor.
142 * @return A new key descriptor.
143 */
144 private KeyDescriptor makeKeyDescriptor(@NonNull String alias) {
145 KeyDescriptor descriptor = new KeyDescriptor();
146 descriptor.domain = getTargetDomain();
147 descriptor.nspace = mNamespace; // ignored if Domain.App;
148 descriptor.alias = alias;
149 descriptor.blob = null;
150 return descriptor;
151 }
152
153 private @Domain int getTargetDomain() {
154 return mNamespace == KeyProperties.NAMESPACE_APPLICATION
155 ? Domain.APP
156 : Domain.SELINUX;
157 }
158 private KeyEntryResponse getKeyMetadata(String alias) {
159 if (alias == null) {
160 throw new NullPointerException("alias == null");
161 }
162
163 KeyDescriptor descriptor = makeKeyDescriptor(alias);
164
165 try {
166 return mKeyStore.getKeyEntry(descriptor);
167 } catch (android.security.KeyStoreException e) {
168 if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) {
169 Log.w(TAG, "Could not get key metadata from Keystore.", e);
170 }
171 return null;
172 }
173 }
174
175 @Override
176 public Certificate[] engineGetCertificateChain(String alias) {
177 KeyEntryResponse response = getKeyMetadata(alias);
178
179 if (response == null || response.metadata.certificate == null) {
180 return null;
181 }
182
183 final X509Certificate leaf = (X509Certificate) toCertificate(response.metadata.certificate);
184 if (leaf == null) {
185 return null;
186 }
187
188 final Certificate[] caList;
189
190 final byte[] caBytes = response.metadata.certificateChain;
191
192 if (caBytes != null) {
193 final Collection<X509Certificate> caChain = toCertificates(caBytes);
194
195 caList = new Certificate[caChain.size() + 1];
196
197 final Iterator<X509Certificate> it = caChain.iterator();
198 int i = 1;
199 while (it.hasNext()) {
200 caList[i++] = it.next();
201 }
202 } else {
203 caList = new Certificate[1];
204 }
205
206 caList[0] = leaf;
207
208 return caList;
209 }
210
211 @Override
212 public Certificate engineGetCertificate(String alias) {
213 KeyEntryResponse response = getKeyMetadata(alias);
214
215 if (response == null) {
216 return null;
217 }
218
219 byte[] encodedCert = response.metadata.certificate;
220 if (encodedCert != null) {
221 return toCertificate(encodedCert);
222 }
223
224 encodedCert = response.metadata.certificateChain;
225 if (encodedCert != null) {
226 return toCertificate(encodedCert);
227 }
228
229 // This entry/alias does not contain a certificate.
230 return null;
231 }
232
233 static X509Certificate toCertificate(byte[] bytes) {
234 try {
235 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
236 return (X509Certificate) certFactory.generateCertificate(
237 new ByteArrayInputStream(bytes));
238 } catch (CertificateException e) {
239 Log.w(NAME, "Couldn't parse certificate in keystore", e);
240 return null;
241 }
242 }
243
244 @SuppressWarnings("unchecked")
245 private static Collection<X509Certificate> toCertificates(byte[] bytes) {
246 try {
247 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
248 return (Collection<X509Certificate>) certFactory.generateCertificates(
249 new ByteArrayInputStream(bytes));
250 } catch (CertificateException e) {
251 Log.w(NAME, "Couldn't parse certificates in keystore", e);
252 return new ArrayList<X509Certificate>();
253 }
254 }
255
256 @Override
257 public Date engineGetCreationDate(String alias) {
258 KeyEntryResponse response = getKeyMetadata(alias);
259
260 if (response == null) {
261 return null;
262 }
263
264 if (response.metadata.modificationTimeMs == -1) {
265 return null;
266 }
267 return new Date(response.metadata.modificationTimeMs);
268 }
269
270 @Override
271 public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
272 throws KeyStoreException {
273 if ((password != null) && (password.length > 0)) {
274 throw new KeyStoreException("entries cannot be protected with passwords");
275 }
276
277 if (key instanceof PrivateKey) {
278 setPrivateKeyEntry(alias, (PrivateKey) key, chain, null);
279 } else if (key instanceof SecretKey) {
280 setSecretKeyEntry(alias, (SecretKey) key, null);
281 } else {
282 throw new KeyStoreException("Only PrivateKey and SecretKey are supported");
283 }
284 }
285
286 private static KeyProtection getLegacyKeyProtectionParameter(PrivateKey key)
287 throws KeyStoreException {
288 String keyAlgorithm = key.getAlgorithm();
289 KeyProtection.Builder specBuilder;
290 if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
291 specBuilder =
292 new KeyProtection.Builder(
293 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
294 // Authorized to be used with any digest (including no digest).
295 // MD5 was never offered for Android Keystore for ECDSA.
296 specBuilder.setDigests(
297 KeyProperties.DIGEST_NONE,
298 KeyProperties.DIGEST_SHA1,
299 KeyProperties.DIGEST_SHA224,
300 KeyProperties.DIGEST_SHA256,
301 KeyProperties.DIGEST_SHA384,
302 KeyProperties.DIGEST_SHA512);
303 } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
304 specBuilder =
305 new KeyProtection.Builder(
306 KeyProperties.PURPOSE_ENCRYPT
307 | KeyProperties.PURPOSE_DECRYPT
308 | KeyProperties.PURPOSE_SIGN
309 | KeyProperties.PURPOSE_VERIFY);
310 // Authorized to be used with any digest (including no digest).
311 specBuilder.setDigests(
312 KeyProperties.DIGEST_NONE,
313 KeyProperties.DIGEST_MD5,
314 KeyProperties.DIGEST_SHA1,
315 KeyProperties.DIGEST_SHA224,
316 KeyProperties.DIGEST_SHA256,
317 KeyProperties.DIGEST_SHA384,
318 KeyProperties.DIGEST_SHA512);
319 // Authorized to be used with any encryption and signature padding
320 // schemes (including no padding).
321 specBuilder.setEncryptionPaddings(
322 KeyProperties.ENCRYPTION_PADDING_NONE,
323 KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1,
324 KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
325 specBuilder.setSignaturePaddings(
326 KeyProperties.SIGNATURE_PADDING_RSA_PKCS1,
327 KeyProperties.SIGNATURE_PADDING_RSA_PSS);
328 // Disable randomized encryption requirement to support encryption
329 // padding NONE above.
330 specBuilder.setRandomizedEncryptionRequired(false);
331 } else {
332 throw new KeyStoreException("Unsupported key algorithm: " + keyAlgorithm);
333 }
334 specBuilder.setUserAuthenticationRequired(false);
335
336 return specBuilder.build();
337 }
338
339 private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain,
340 java.security.KeyStore.ProtectionParameter param) throws KeyStoreException {
341 @SecurityLevel int securitylevel = SecurityLevel.TRUSTED_ENVIRONMENT;
342 int flags = 0;
343 KeyProtection spec;
344 if (param == null) {
345 spec = getLegacyKeyProtectionParameter(key);
346 } else if (param instanceof KeyStoreParameter) {
347 spec = getLegacyKeyProtectionParameter(key);
348 KeyStoreParameter legacySpec = (KeyStoreParameter) param;
349 } else if (param instanceof KeyProtection) {
350 spec = (KeyProtection) param;
351 if (spec.isCriticalToDeviceEncryption()) {
352 // This key is should not be bound to the LSKF even if it is auth bound.
353 // This indicates that this key is used in the derivation for of the
354 // master key, that is used for the LSKF binding of other auth bound
355 // keys. This breaks up a circular dependency while retaining logical
356 // authentication binding of the key.
357 flags |= IKeystoreSecurityLevel
358 .KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING;
359 }
360
361 if (spec.isStrongBoxBacked()) {
362 securitylevel = SecurityLevel.STRONGBOX;
363 }
364 } else {
365 throw new KeyStoreException(
366 "Unsupported protection parameter class:" + param.getClass().getName()
367 + ". Supported: " + KeyProtection.class.getName() + ", "
368 + KeyStoreParameter.class.getName());
369 }
370
371 // Make sure the chain exists since this is a PrivateKey
372 if ((chain == null) || (chain.length == 0)) {
373 throw new KeyStoreException("Must supply at least one Certificate with PrivateKey");
374 }
375
376 // Do chain type checking.
377 X509Certificate[] x509chain = new X509Certificate[chain.length];
378 for (int i = 0; i < chain.length; i++) {
379 if (!"X.509".equals(chain[i].getType())) {
380 throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #"
381 + i);
382 }
383
384 if (!(chain[i] instanceof X509Certificate)) {
385 throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #"
386 + i);
387 }
388
389 x509chain[i] = (X509Certificate) chain[i];
390 }
391
392 final byte[] userCertBytes;
393 try {
394 userCertBytes = x509chain[0].getEncoded();
395 } catch (CertificateEncodingException e) {
396 throw new KeyStoreException("Failed to encode certificate #0", e);
397 }
398
399 /*
400 * If we have a chain, store it in the CA certificate slot for this
401 * alias as concatenated DER-encoded certificates. These can be
402 * deserialized by {@link CertificateFactory#generateCertificates}.
403 */
404 final byte[] chainBytes;
405 if (chain.length > 1) {
406 /*
407 * The chain is passed in as {user_cert, ca_cert_1, ca_cert_2, ...}
408 * so we only need the certificates starting at index 1.
409 */
410 final byte[][] certsBytes = new byte[x509chain.length - 1][];
411 int totalCertLength = 0;
412 for (int i = 0; i < certsBytes.length; i++) {
413 try {
414 certsBytes[i] = x509chain[i + 1].getEncoded();
415 totalCertLength += certsBytes[i].length;
416 } catch (CertificateEncodingException e) {
417 throw new KeyStoreException("Failed to encode certificate #" + i, e);
418 }
419 }
420
421 /*
422 * Serialize this into one byte array so we can later call
423 * CertificateFactory#generateCertificates to recover them.
424 */
425 chainBytes = new byte[totalCertLength];
426 int outputOffset = 0;
427 for (int i = 0; i < certsBytes.length; i++) {
428 final int certLength = certsBytes[i].length;
429 System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength);
430 outputOffset += certLength;
431 certsBytes[i] = null;
432 }
433 } else {
434 chainBytes = null;
435 }
436
437 @Domain int targetDomain = getTargetDomain();
438
439 // If the given key is an AndroidKeyStorePrivateKey, we attempt to update
440 // its subcomponents with the given certificate and certificate chain.
441 if (key instanceof AndroidKeyStorePrivateKey) {
442 AndroidKeyStoreKey ksKey = (AndroidKeyStoreKey) key;
443 KeyDescriptor descriptor = ksKey.getUserKeyDescriptor();
444
445 // This throws if the request cannot replace the entry.
446 assertCanReplace(alias, targetDomain, mNamespace, descriptor);
447
448 try {
449 mKeyStore.updateSubcomponents(
450 ((AndroidKeyStorePrivateKey) key).getKeyIdDescriptor(),
451 userCertBytes, chainBytes);
452 } catch (android.security.KeyStoreException e) {
453 throw new KeyStoreException("Failed to store certificate and certificate chain", e);
454 }
455 return;
456 }
457
458 // Make sure the PrivateKey format is the one we support.
459 final String keyFormat = key.getFormat();
460 if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) {
461 throw new KeyStoreException(
462 "Unsupported private key export format: " + keyFormat
463 + ". Only private keys which export their key material in PKCS#8 format are"
464 + " supported.");
465 }
466
467 // Make sure we can actually encode the key.
468 byte[] pkcs8EncodedPrivateKeyBytes = key.getEncoded();
469 if (pkcs8EncodedPrivateKeyBytes == null) {
470 throw new KeyStoreException("Private key did not export any key material");
471 }
472
473 final List<KeyParameter> importArgs = new ArrayList<>();
474
475 try {
476 importArgs.add(KeyStore2ParameterUtils.makeEnum(
477 KeymasterDefs.KM_TAG_ALGORITHM,
478 KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(
479 key.getAlgorithm()))
480 );
481 KeyStore2ParameterUtils.forEachSetFlag(spec.getPurposes(), (purpose) -> {
482 importArgs.add(KeyStore2ParameterUtils.makeEnum(
483 KeymasterDefs.KM_TAG_PURPOSE,
484 KeyProperties.Purpose.toKeymaster(purpose)
485 ));
486 });
487 if (spec.isDigestsSpecified()) {
488 for (String digest : spec.getDigests()) {
489 importArgs.add(KeyStore2ParameterUtils.makeEnum(
490 KeymasterDefs.KM_TAG_DIGEST,
491 KeyProperties.Digest.toKeymaster(digest)
492 ));
493 }
494 }
495 for (String blockMode : spec.getBlockModes()) {
496 importArgs.add(KeyStore2ParameterUtils.makeEnum(
497 KeymasterDefs.KM_TAG_BLOCK_MODE,
498 KeyProperties.BlockMode.toKeymaster(blockMode)
499 ));
500 }
501 int[] keymasterEncryptionPaddings =
502 KeyProperties.EncryptionPadding.allToKeymaster(
503 spec.getEncryptionPaddings());
504 if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0)
505 && (spec.isRandomizedEncryptionRequired())) {
506 for (int keymasterPadding : keymasterEncryptionPaddings) {
507 if (!KeymasterUtils
508 .isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(
509 keymasterPadding)) {
510 throw new KeyStoreException(
511 "Randomized encryption (IND-CPA) required but is violated by"
512 + " encryption padding mode: "
513 + KeyProperties.EncryptionPadding.fromKeymaster(
514 keymasterPadding)
515 + ". See KeyProtection documentation.");
516 }
517 }
518 }
519 for (int padding : keymasterEncryptionPaddings) {
520 importArgs.add(KeyStore2ParameterUtils.makeEnum(
521 KeymasterDefs.KM_TAG_PADDING,
522 padding
523 ));
524 if (padding == KeymasterDefs.KM_PAD_RSA_OAEP) {
525 if (spec.isDigestsSpecified()) {
526 boolean hasDefaultMgf1DigestBeenAdded = false;
527 for (String digest : spec.getDigests()) {
528 importArgs.add(KeyStore2ParameterUtils.makeEnum(
529 KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
530 KeyProperties.Digest.toKeymaster(digest)
531 ));
532 hasDefaultMgf1DigestBeenAdded |= digest.equals(DEFAULT_MGF1_DIGEST);
533 }
534 /* Because of default MGF1 digest is SHA-1. It has to be added in Key
535 * characteristics. Otherwise, crypto operations will fail with Incompatible
536 * MGF1 digest.
537 */
538 if (!hasDefaultMgf1DigestBeenAdded) {
539 importArgs.add(KeyStore2ParameterUtils.makeEnum(
540 KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
541 KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
542 ));
543 }
544 }
545 }
546 }
547 for (String padding : spec.getSignaturePaddings()) {
548 importArgs.add(KeyStore2ParameterUtils.makeEnum(
549 KeymasterDefs.KM_TAG_PADDING,
550 KeyProperties.SignaturePadding.toKeymaster(padding)
551 ));
552 }
553 KeyStore2ParameterUtils.addUserAuthArgs(importArgs, spec);
554 if (spec.getKeyValidityStart() != null) {
555 importArgs.add(KeyStore2ParameterUtils.makeDate(
556 KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart()
557 ));
558 }
559 if (spec.getKeyValidityForOriginationEnd() != null) {
560 importArgs.add(KeyStore2ParameterUtils.makeDate(
561 KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
562 spec.getKeyValidityForOriginationEnd()
563 ));
564 }
565 if (spec.getKeyValidityForConsumptionEnd() != null) {
566 importArgs.add(KeyStore2ParameterUtils.makeDate(
567 KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
568 spec.getKeyValidityForConsumptionEnd()
569 ));
570 }
571 if (spec.getMaxUsageCount() != KeyProperties.UNRESTRICTED_USAGE_COUNT) {
572 importArgs.add(KeyStore2ParameterUtils.makeInt(
573 KeymasterDefs.KM_TAG_USAGE_COUNT_LIMIT,
574 spec.getMaxUsageCount()
575 ));
576 }
577 if (KeymasterDefs.KM_ALGORITHM_EC
578 == KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(
579 key.getAlgorithm())) {
580 importArgs.add(KeyStore2ParameterUtils.makeEnum(
581 KeymasterDefs.KM_TAG_EC_CURVE,
582 getKeymasterEcCurve(key)
583 ));
584 }
585 } catch (IllegalArgumentException | IllegalStateException e) {
586 throw new KeyStoreException(e);
587 }
588
589 try {
590 KeyStoreSecurityLevel securityLevelInterface = mKeyStore.getSecurityLevel(
591 securitylevel);
592
593 KeyDescriptor descriptor = makeKeyDescriptor(alias);
594
595 KeyMetadata metadata = securityLevelInterface.importKey(descriptor, null,
596 importArgs, flags, pkcs8EncodedPrivateKeyBytes);
597
598 try {
599 mKeyStore.updateSubcomponents(metadata.key, userCertBytes, chainBytes);
600 } catch (android.security.KeyStoreException e) {
601 mKeyStore.deleteKey(metadata.key);
602 throw new KeyStoreException("Failed to store certificate and certificate chain", e);
603 }
604
605 } catch (android.security.KeyStoreException e) {
606 throw new KeyStoreException("Failed to store private key", e);
607 }
608 }
609
610 private int getKeymasterEcCurve(PrivateKey key) {
611 if (key instanceof ECKey) {
612 ECParameterSpec param = ((ECPrivateKey) key).getParams();
613 int kmECCurve = KeymasterUtils.getKeymasterEcCurve(KeymasterUtils.getCurveName(param));
614 if (kmECCurve >= 0) {
615 return kmECCurve;
616 }
617 } else if (key instanceof XECKey) {
618 AlgorithmParameterSpec param = ((XECPrivateKey) key).getParams();
619 if (param.equals(NamedParameterSpec.X25519)) {
620 return EcCurve.CURVE_25519;
621 }
622 } else if (key.getAlgorithm().equals("XDH")) {
623 // TODO com.android.org.conscrypt.OpenSSLX25519PrivateKey does not implement XECKey,
624 // this case is not required once it implements XECKey interface(b/214203951).
625 return EcCurve.CURVE_25519;
626 } else if (key instanceof EdECKey) {
627 AlgorithmParameterSpec param = ((EdECPrivateKey) key).getParams();
628 if (param.equals(NamedParameterSpec.ED25519)) {
629 return EcCurve.CURVE_25519;
630 }
631 }
632 throw new IllegalArgumentException("Unexpected Key " + key.getClass().getName());
633 }
634
635 private static void assertCanReplace(String alias, @Domain int targetDomain,
636 int targetNamespace, KeyDescriptor descriptor)
637 throws KeyStoreException {
638 // If
639 // * the alias does not match, or
640 // * the domain does not match, or
641 // * the domain is Domain.SELINUX and the namespaces don not match,
642 // then the designated key location is not equivalent to the location of the
643 // given key parameter and cannot be updated.
644 //
645 // Note: mNamespace == KeyProperties.NAMESPACE_APPLICATION implies that the target domain
646 // is Domain.APP and Domain.SELINUX is the target domain otherwise.
647 if (!alias.equals(descriptor.alias)
648 || descriptor.domain != targetDomain
649 || (descriptor.domain == Domain.SELINUX && descriptor.nspace != targetNamespace)) {
650 throw new KeyStoreException("Can only replace keys with same alias: " + alias
651 + " != " + descriptor.alias + " in the same target domain: " + targetDomain
652 + " != " + descriptor.domain
653 + (targetDomain == Domain.SELINUX ? " in the same target namespace: "
654 + targetNamespace + " != " + descriptor.nspace : "")
655 );
656 }
657 }
658
659 private void setSecretKeyEntry(String alias, SecretKey key,
660 java.security.KeyStore.ProtectionParameter param)
661 throws KeyStoreException {
662 if ((param != null) && (!(param instanceof KeyProtection))) {
663 throw new KeyStoreException(
664 "Unsupported protection parameter class: " + param.getClass().getName()
665 + ". Supported: " + KeyProtection.class.getName());
666 }
667 KeyProtection params = (KeyProtection) param;
668
669 @Domain int targetDomain = (getTargetDomain());
670
671 if (key instanceof AndroidKeyStoreSecretKey) {
672 String keyAliasInKeystore =
673 ((AndroidKeyStoreSecretKey) key).getUserKeyDescriptor().alias;
674
675 KeyDescriptor descriptor = ((AndroidKeyStoreSecretKey) key).getUserKeyDescriptor();
676
677 // This throws if the request cannot replace the existing key.
678 assertCanReplace(alias, targetDomain, mNamespace, descriptor);
679
680 // This is the entry where this key is already stored. No need to do anything.
681 if (params != null) {
682 throw new KeyStoreException("Modifying KeyStore-backed key using protection"
683 + " parameters not supported");
684 }
685 return;
686 }
687
688 if (params == null) {
689 throw new KeyStoreException(
690 "Protection parameters must be specified when importing a symmetric key");
691 }
692
693 // Not a KeyStore-backed secret key -- import its key material into keystore.
694 String keyExportFormat = key.getFormat();
695 if (keyExportFormat == null) {
696 throw new KeyStoreException(
697 "Only secret keys that export their key material are supported");
698 } else if (!"RAW".equals(keyExportFormat)) {
699 throw new KeyStoreException(
700 "Unsupported secret key material export format: " + keyExportFormat);
701 }
702 byte[] keyMaterial = key.getEncoded();
703 if (keyMaterial == null) {
704 throw new KeyStoreException("Key did not export its key material despite supporting"
705 + " RAW format export");
706 }
707
708 final List<KeyParameter> importArgs = new ArrayList<>();
709
710 try {
711 int keymasterAlgorithm =
712 KeyProperties.KeyAlgorithm.toKeymasterSecretKeyAlgorithm(
713 key.getAlgorithm());
714
715 importArgs.add(KeyStore2ParameterUtils.makeEnum(
716 KeymasterDefs.KM_TAG_ALGORITHM,
717 keymasterAlgorithm
718 ));
719
720 if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
721 // JCA HMAC key algorithm implies a digest (e.g., HmacSHA256 key algorithm
722 // implies SHA-256 digest). Because keymaster HMAC key is authorized only for one
723 // digest, we don't let import parameters override the digest implied by the key.
724 // If the parameters specify digests at all, they must specify only one digest, the
725 // only implied by key algorithm.
726 int keymasterImpliedDigest =
727 KeyProperties.KeyAlgorithm.toKeymasterDigest(key.getAlgorithm());
728 if (keymasterImpliedDigest == -1) {
729 throw new ProviderException(
730 "HMAC key algorithm digest unknown for key algorithm "
731 + key.getAlgorithm());
732 }
733
734 if (params.isDigestsSpecified()) {
735 // Digest(s) explicitly specified in params -- check that the list consists of
736 // exactly one digest, the one implied by key algorithm.
737 int[] keymasterDigestsFromParams =
738 KeyProperties.Digest.allToKeymaster(params.getDigests());
739 if ((keymasterDigestsFromParams.length != 1)
740 || (keymasterDigestsFromParams[0] != keymasterImpliedDigest)) {
741 throw new KeyStoreException(
742 "Unsupported digests specification: "
743 + Arrays.asList(params.getDigests()) + ". Only "
744 + KeyProperties.Digest.fromKeymaster(keymasterImpliedDigest)
745 + " supported for HMAC key algorithm "
746 + key.getAlgorithm());
747 }
748 }
749 int outputBits = KeymasterUtils.getDigestOutputSizeBits(keymasterImpliedDigest);
750 if (outputBits == -1) {
751 throw new ProviderException(
752 "HMAC key authorized for unsupported digest: "
753 + KeyProperties.Digest.fromKeymaster(keymasterImpliedDigest));
754 }
755 importArgs.add(KeyStore2ParameterUtils.makeEnum(
756 KeymasterDefs.KM_TAG_DIGEST, keymasterImpliedDigest
757 ));
758 importArgs.add(KeyStore2ParameterUtils.makeInt(
759 KeymasterDefs.KM_TAG_MIN_MAC_LENGTH, outputBits
760 ));
761 } else {
762 if (params.isDigestsSpecified()) {
763 for (String digest : params.getDigests()) {
764 importArgs.add(KeyStore2ParameterUtils.makeEnum(
765 KeymasterDefs.KM_TAG_DIGEST,
766 KeyProperties.Digest.toKeymaster(digest)
767 ));
768 }
769 }
770 }
771
772 KeyStore2ParameterUtils.forEachSetFlag(params.getPurposes(), (purpose) -> {
773 importArgs.add(KeyStore2ParameterUtils.makeEnum(
774 KeymasterDefs.KM_TAG_PURPOSE,
775 KeyProperties.Purpose.toKeymaster(purpose)
776 ));
777 });
778
779 boolean indCpa = false;
780 if ((params.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) {
781 if (((KeyProtection) param).isRandomizedEncryptionRequired()) {
782 indCpa = true;
783 } else {
784 importArgs.add(KeyStore2ParameterUtils.makeBool(
785 KeymasterDefs.KM_TAG_CALLER_NONCE
786 ));
787 }
788 }
789
790 for (String blockMode : params.getBlockModes()) {
791 int keymasterBlockMode = KeyProperties.BlockMode.toKeymaster(blockMode);
792 if (indCpa
793 && !KeymasterUtils.isKeymasterBlockModeIndCpaCompatibleWithSymmetricCrypto(
794 keymasterBlockMode)) {
795 throw new KeyStoreException(
796 "Randomized encryption (IND-CPA) required but may be violated by"
797 + " block mode: " + blockMode
798 + ". See KeyProtection documentation.");
799
800 }
801 if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_AES
802 && keymasterBlockMode == KeymasterDefs.KM_MODE_GCM) {
803 importArgs.add(KeyStore2ParameterUtils.makeInt(
804 KeymasterDefs.KM_TAG_MIN_MAC_LENGTH,
805 AndroidKeyStoreAuthenticatedAESCipherSpi.GCM
806 .MIN_SUPPORTED_TAG_LENGTH_BITS
807 ));
808 }
809 importArgs.add(KeyStore2ParameterUtils.makeEnum(
810 KeymasterDefs.KM_TAG_BLOCK_MODE,
811 keymasterBlockMode
812 ));
813 }
814
815 if (params.getSignaturePaddings().length > 0) {
816 throw new KeyStoreException("Signature paddings not supported for symmetric keys");
817 }
818
819 for (String padding : params.getEncryptionPaddings()) {
820 importArgs.add(KeyStore2ParameterUtils.makeEnum(
821 KeymasterDefs.KM_TAG_PADDING,
822 KeyProperties.EncryptionPadding.toKeymaster(padding)
823 ));
824 }
825
826 KeyStore2ParameterUtils.addUserAuthArgs(importArgs, params);
827
828 if (params.getKeyValidityStart() != null) {
829 importArgs.add(KeyStore2ParameterUtils.makeDate(
830 KeymasterDefs.KM_TAG_ACTIVE_DATETIME, params.getKeyValidityStart()
831 ));
832 }
833 if (params.getKeyValidityForOriginationEnd() != null) {
834 importArgs.add(KeyStore2ParameterUtils.makeDate(
835 KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
836 params.getKeyValidityForOriginationEnd()
837 ));
838 }
839 if (params.getKeyValidityForConsumptionEnd() != null) {
840 importArgs.add(KeyStore2ParameterUtils.makeDate(
841 KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
842 params.getKeyValidityForConsumptionEnd()
843 ));
844 }
845 if (params.getMaxUsageCount() != KeyProperties.UNRESTRICTED_USAGE_COUNT) {
846 importArgs.add(KeyStore2ParameterUtils.makeInt(
847 KeymasterDefs.KM_TAG_USAGE_COUNT_LIMIT,
848 params.getMaxUsageCount()
849 ));
850 }
851 } catch (IllegalArgumentException | IllegalStateException e) {
852 throw new KeyStoreException(e);
853 }
854
855 int flags = 0;
856 if (params.isCriticalToDeviceEncryption()) {
857 flags |= IKeystoreSecurityLevel.KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING;
858 }
859
860 @SecurityLevel int securityLevel = params.isStrongBoxBacked() ? SecurityLevel.STRONGBOX :
861 SecurityLevel.TRUSTED_ENVIRONMENT;
862
863 try {
864 KeyStoreSecurityLevel securityLevelInterface = mKeyStore.getSecurityLevel(
865 securityLevel);
866
867 KeyDescriptor descriptor = makeKeyDescriptor(alias);
868
869 securityLevelInterface.importKey(descriptor, null /* TODO attestationKey */,
870 importArgs, flags, keyMaterial);
871 } catch (android.security.KeyStoreException e) {
872 throw new KeyStoreException("Failed to import secret key.", e);
873 }
874 }
875
876 private void setWrappedKeyEntry(String alias, WrappedKeyEntry entry,
877 java.security.KeyStore.ProtectionParameter param) throws KeyStoreException {
878 if (param != null) {
879 throw new KeyStoreException("Protection parameters are specified inside wrapped keys");
880 }
881
882 byte[] maskingKey = new byte[32];
883
884 String[] parts = entry.getTransformation().split("/");
885
886 List<KeyParameter> args = new ArrayList<>();
887
888 String algorithm = parts[0];
889 if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(algorithm)) {
890 args.add(KeyStore2ParameterUtils.makeEnum(
891 KeymasterDefs.KM_TAG_ALGORITHM,
892 KeymasterDefs.KM_ALGORITHM_RSA
893 ));
894 } else {
895 throw new KeyStoreException("Algorithm \"" + algorithm + "\" not supported for "
896 + "wrapping. Only RSA wrapping keys are supported.");
897 }
898
899 if (parts.length > 1) {
900 String mode = parts[1];
901 args.add(KeyStore2ParameterUtils.makeEnum(
902 KeymasterDefs.KM_TAG_BLOCK_MODE,
903 KeyProperties.BlockMode.toKeymaster(mode)
904 ));
905 }
906
907 if (parts.length > 2) {
908 @KeyProperties.EncryptionPaddingEnum int padding =
909 KeyProperties.EncryptionPadding.toKeymaster(parts[2]);
910 if (padding != KeymasterDefs.KM_PAD_NONE) {
911 args.add(KeyStore2ParameterUtils.makeEnum(
912 KeymasterDefs.KM_TAG_PADDING,
913 padding
914 ));
915 }
916 }
917
918 KeyGenParameterSpec spec = (KeyGenParameterSpec) entry.getAlgorithmParameterSpec();
919 if (spec.isDigestsSpecified()) {
920 @KeyProperties.DigestEnum int digest =
921 KeyProperties.Digest.toKeymaster(spec.getDigests()[0]);
922 if (digest != KeymasterDefs.KM_DIGEST_NONE) {
923 args.add(KeyStore2ParameterUtils.makeEnum(
924 KeymasterDefs.KM_TAG_DIGEST,
925 digest
926 ));
927 }
928 }
929
930 KeyDescriptor wrappingkey = makeKeyDescriptor(entry.getWrappingKeyAlias());
931
932 KeyEntryResponse response = null;
933 try {
934 response = mKeyStore.getKeyEntry(wrappingkey);
935 } catch (android.security.KeyStoreException e) {
936 throw new KeyStoreException("Failed to import wrapped key. Keystore error code: "
937 + e.getErrorCode(), e);
938 }
939
940 KeyDescriptor wrappedKey = makeKeyDescriptor(alias);
941
942 KeyStoreSecurityLevel securityLevel = new KeyStoreSecurityLevel(response.iSecurityLevel);
943
944 final BiometricManager bm = android.app.AppGlobals.getInitialApplication()
945 .getSystemService(BiometricManager.class);
946
947 long[] biometricSids = bm.getAuthenticatorIds();
948
949 List<AuthenticatorSpec> authenticatorSpecs = new ArrayList<>();
950
951 AuthenticatorSpec authenticatorSpec = new AuthenticatorSpec();
952 authenticatorSpec.authenticatorType = HardwareAuthenticatorType.PASSWORD;
953 authenticatorSpec.authenticatorId = GateKeeper.getSecureUserId();
954 authenticatorSpecs.add(authenticatorSpec);
955
956 for (long sid : biometricSids) {
957 AuthenticatorSpec authSpec = new AuthenticatorSpec();
958 authSpec.authenticatorType = HardwareAuthenticatorType.FINGERPRINT;
959 authSpec.authenticatorId = sid;
960 authenticatorSpecs.add(authSpec);
961 }
962
963 try {
964 securityLevel.importWrappedKey(
965 wrappedKey, wrappingkey,
966 entry.getWrappedKeyBytes(),
967 null /* masking key is set to 32 bytes if null is given here */,
968 args,
969 authenticatorSpecs.toArray(new AuthenticatorSpec[0]));
970 } catch (android.security.KeyStoreException e) {
971 switch (e.getErrorCode()) {
972 case KeymasterDefs.KM_ERROR_UNIMPLEMENTED: {
973 throw new SecureKeyImportUnavailableException("Could not import wrapped key");
974 }
975 default:
976 throw new KeyStoreException("Failed to import wrapped key. Keystore error "
977 + "code: " + e.getErrorCode(), e);
978 }
979 }
980 }
981
982 @Override
983 public void engineSetKeyEntry(String alias, byte[] userKey, Certificate[] chain)
984 throws KeyStoreException {
985 throw new KeyStoreException("Operation not supported because key encoding is unknown");
986 }
987
988 /**
989 * This function sets a trusted certificate entry. It fails if the given
990 * alias is already taken by an actual key entry. However, if the entry is a
991 * trusted certificate it will get silently replaced.
992 * @param alias the alias name
993 * @param cert the certificate
994 *
995 * @throws KeyStoreException if the alias is already taken by a secret or private
996 * key entry.
997 * @throws KeyStoreException with a nested {@link CertificateEncodingException}
998 * if the {@code cert.getEncoded()} throws.
999 * @throws KeyStoreException with a nested {@link android.security.KeyStoreException} if
1000 * something went wrong while inserting the certificate into keystore.
1001 * @throws NullPointerException if cert or alias is null.
1002 *
1003 * @hide
1004 */
1005 @Override
1006 public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException {
1007 if (isKeyEntry(alias)) {
1008 throw new KeyStoreException("Entry exists and is not a trusted certificate");
1009 }
1010
1011 // We can't set something to null.
1012 if (cert == null) {
1013 throw new NullPointerException("cert == null");
1014 }
1015
1016 final byte[] encoded;
1017 try {
1018 encoded = cert.getEncoded();
1019 } catch (CertificateEncodingException e) {
1020 throw new KeyStoreException(e);
1021 }
1022
1023 try {
1024 mKeyStore.updateSubcomponents(makeKeyDescriptor(alias),
1025 null /* publicCert - unused when used as pure certificate store. */,
1026 encoded);
1027 } catch (android.security.KeyStoreException e) {
1028 throw new KeyStoreException("Couldn't insert certificate.", e);
1029 }
1030 }
1031
1032 @Override
1033 public void engineDeleteEntry(String alias) throws KeyStoreException {
1034 KeyDescriptor descriptor = makeKeyDescriptor(alias);
1035 try {
1036 mKeyStore.deleteKey(descriptor);
1037 } catch (android.security.KeyStoreException e) {
1038 if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) {
1039 throw new KeyStoreException("Failed to delete entry: " + alias, e);
1040 }
1041 }
1042 }
1043
1044 private KeyDescriptor[] getAliasesBatch(String startPastAlias) {
1045 try {
1046 return mKeyStore.listBatch(
1047 getTargetDomain(),
1048 mNamespace,
1049 startPastAlias
1050 );
1051 } catch (android.security.KeyStoreException e) {
1052 Log.e(TAG, "Failed to list keystore entries.", e);
1053 return new KeyDescriptor[0];
1054 }
1055 }
1056
1057 @Override
1058 public Enumeration<String> engineAliases() {
1059 return new KeyEntriesEnumerator();
1060 }
1061
1062 @Override
1063 public boolean engineContainsAlias(String alias) {
1064 if (alias == null) {
1065 throw new NullPointerException("alias == null");
1066 }
1067
1068 return getKeyMetadata(alias) != null;
1069 }
1070 @Override
1071 public int engineSize() {
1072 try {
1073 return mKeyStore.getNumberOfEntries(
1074 getTargetDomain(),
1075 mNamespace
1076 );
1077 } catch (android.security.KeyStoreException e) {
1078 Log.e(TAG, "Failed to get the number of keystore entries.", e);
1079 return 0;
1080 }
1081 }
1082 @Override
1083 public boolean engineIsKeyEntry(String alias) {
1084 return isKeyEntry(alias);
1085 }
1086
1087 private boolean isKeyEntry(String alias) {
1088 if (alias == null) {
1089 throw new NullPointerException("alias == null");
1090 }
1091
1092 KeyEntryResponse response = getKeyMetadata(alias);
1093 // If response is null, there is no such entry.
1094 // If response.iSecurityLevel is null, there is no private or secret key material stored.
1095 return response != null && response.iSecurityLevel != null;
1096 }
1097
1098
1099 @Override
1100 public boolean engineIsCertificateEntry(String alias) {
1101 if (alias == null) {
1102 throw new NullPointerException("alias == null");
1103 }
1104 KeyEntryResponse response = getKeyMetadata(alias);
1105 // If response == null there is no such entry.
1106 // If there is no certificateChain, then this is not a certificate entry.
1107 // If there is a private key entry, this is the certificate chain for that
1108 // key entry and not a CA certificate entry.
1109 return response != null
1110 && response.metadata.certificateChain != null
1111 && response.iSecurityLevel == null;
1112 }
1113
1114 @Override
1115 public String engineGetCertificateAlias(Certificate cert) {
1116 if (cert == null) {
1117 return null;
1118 }
1119 if (!"X.509".equalsIgnoreCase(cert.getType())) {
1120 Log.e(TAG, "In engineGetCertificateAlias: only X.509 certificates are supported.");
1121 return null;
1122 }
1123 byte[] targetCertBytes;
1124 try {
1125 targetCertBytes = cert.getEncoded();
1126 } catch (CertificateEncodingException e) {
1127 Log.e(TAG, "While trying to get the alias for a certificate.", e);
1128 return null;
1129 }
1130 if (targetCertBytes == null) {
1131 return null;
1132 }
1133
1134 KeyDescriptor[] keyDescriptors = null;
1135 try {
1136 keyDescriptors = mKeyStore.list(
1137 getTargetDomain(),
1138 mNamespace
1139 );
1140 } catch (android.security.KeyStoreException e) {
1141 Log.w(TAG, "Failed to get list of keystore entries.", e);
1142 }
1143
1144 String caAlias = null;
1145 for (KeyDescriptor d : keyDescriptors) {
1146 KeyEntryResponse response = getKeyMetadata(d.alias);
1147 if (response == null) {
1148 continue;
1149 }
1150 /*
1151 * The KeyStoreSpi documentation says to only compare the first certificate in the
1152 * chain which is equivalent to the {@code response.metadata.certificate} field.
1153 * So we look for a hit in this field first. For pure CA certificate entries,
1154 * we check the {@code response.metadata.certificateChain} field. But we only
1155 * return a CA alias if there was no hit in the certificate field of any other
1156 * entry.
1157 */
1158 if (response.metadata.certificate != null) {
1159 if (Arrays.equals(response.metadata.certificate, targetCertBytes)) {
1160 return d.alias;
1161 }
1162 } else if (response.metadata.certificateChain != null && caAlias == null) {
1163 if (Arrays.equals(response.metadata.certificateChain, targetCertBytes)) {
1164 caAlias = d.alias;
1165 }
1166 }
1167 }
1168 return caAlias;
1169 }
1170
1171 /**
1172 * Used by Tests to initialize with a fake KeyStore2.
1173 * @hide
1174 * @param keystore
1175 */
1176 @VisibleForTesting
1177 public void initForTesting(KeyStore2 keystore) {
1178 mKeyStore = keystore;
1179 mNamespace = KeyProperties.NAMESPACE_APPLICATION;
1180 }
1181
1182 @Override
1183 public void engineStore(OutputStream stream, char[] password) throws IOException,
1184 NoSuchAlgorithmException, CertificateException {
1185 throw new UnsupportedOperationException("Can not serialize AndroidKeyStore to OutputStream");
1186 }
1187
1188 @Override
1189 public void engineLoad(InputStream stream, char[] password) throws IOException,
1190 NoSuchAlgorithmException, CertificateException {
1191 if (stream != null) {
1192 throw new IllegalArgumentException("InputStream not supported");
1193 }
1194
1195 if (password != null) {
1196 throw new IllegalArgumentException("password not supported");
1197 }
1198
1199 // Unfortunate name collision.
1200 mKeyStore = KeyStore2.getInstance();
1201 mNamespace = KeyProperties.NAMESPACE_APPLICATION;
1202 }
1203
1204 @Override
1205 public void engineLoad(LoadStoreParameter param) throws IOException,
1206 NoSuchAlgorithmException, CertificateException {
1207 @KeyProperties.Namespace int namespace = KeyProperties.NAMESPACE_APPLICATION;
1208 if (param != null) {
1209 if (param instanceof AndroidKeyStoreLoadStoreParameter) {
1210 namespace = ((AndroidKeyStoreLoadStoreParameter) param).getNamespace();
1211 } else {
1212 throw new IllegalArgumentException(
1213 "Unsupported param type: " + param.getClass());
1214 }
1215 }
1216 mKeyStore = KeyStore2.getInstance();
1217 mNamespace = namespace;
1218 }
1219
1220 @Override
1221 public void engineSetEntry(String alias, Entry entry, ProtectionParameter param)
1222 throws KeyStoreException {
1223 if (entry == null) {
1224 throw new KeyStoreException("entry == null");
1225 }
1226
1227 if (entry instanceof java.security.KeyStore.TrustedCertificateEntry) {
1228 java.security.KeyStore.TrustedCertificateEntry trE =
1229 (java.security.KeyStore.TrustedCertificateEntry) entry;
1230 // engineSetCertificateEntry does not overwrite if the existing entry
1231 // is a key entry, but the semantic of engineSetEntry is such that it
1232 // overwrites any existing entry. Thus we delete any possible existing
1233 // entry by this alias.
1234 engineDeleteEntry(alias);
1235 engineSetCertificateEntry(alias, trE.getTrustedCertificate());
1236 return;
1237 }
1238
1239 if (entry instanceof PrivateKeyEntry) {
1240 PrivateKeyEntry prE = (PrivateKeyEntry) entry;
1241 setPrivateKeyEntry(alias, prE.getPrivateKey(), prE.getCertificateChain(), param);
1242 } else if (entry instanceof SecretKeyEntry) {
1243 SecretKeyEntry secE = (SecretKeyEntry) entry;
1244 setSecretKeyEntry(alias, secE.getSecretKey(), param);
1245 } else if (entry instanceof WrappedKeyEntry) {
1246 WrappedKeyEntry wke = (WrappedKeyEntry) entry;
1247 setWrappedKeyEntry(alias, wke, param);
1248 } else {
1249 throw new KeyStoreException(
1250 "Entry must be a PrivateKeyEntry, SecretKeyEntry, WrappedKeyEntry "
1251 + "or TrustedCertificateEntry; was " + entry);
1252 }
1253 }
1254
1255 private class KeyEntriesEnumerator implements Enumeration<String> {
1256 private KeyDescriptor[] mCurrentBatch;
1257 private int mCurrentEntry = 0;
1258 private String mLastAlias = null;
1259 private KeyEntriesEnumerator() {
1260 getAndValidateNextBatch();
1261 }
1262
1263 private void getAndValidateNextBatch() {
1264 mCurrentBatch = getAliasesBatch(mLastAlias);
1265 mCurrentEntry = 0;
1266 }
1267
1268 public boolean hasMoreElements() {
1269 return (mCurrentBatch != null) && (mCurrentBatch.length > 0);
1270 }
1271
1272 public String nextElement() {
1273 if ((mCurrentBatch == null) || (mCurrentBatch.length == 0)) {
1274 throw new NoSuchElementException("Error while fetching entries.");
1275 }
1276 final KeyDescriptor currentEntry = mCurrentBatch[mCurrentEntry];
1277 mLastAlias = currentEntry.alias;
1278
1279 mCurrentEntry++;
1280 // This was the last entry in the batch.
1281 if (mCurrentEntry >= mCurrentBatch.length) {
1282 getAndValidateNextBatch();
1283 }
1284
1285 return mLastAlias;
1286 }
1287 }
1288 }