Debian Codegraph @

keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.security.keystore2;
18
19 import android.annotation.CallSuper;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.hardware.security.keymint.KeyParameter;
23 import android.security.KeyStoreException;
24 import android.security.KeyStoreOperation;
25 import android.security.keymaster.KeymasterDefs;
26 import android.security.keystore.KeyStoreCryptoOperation;
27
28 import libcore.util.EmptyArray;
29
30 import java.nio.BufferOverflowException;
31 import java.nio.ByteBuffer;
32 import java.security.AlgorithmParameters;
33 import java.security.GeneralSecurityException;
34 import java.security.InvalidAlgorithmParameterException;
35 import java.security.InvalidKeyException;
36 import java.security.InvalidParameterException;
37 import java.security.Key;
38 import java.security.KeyFactory;
39 import java.security.NoSuchAlgorithmException;
40 import java.security.PrivateKey;
41 import java.security.ProviderException;
42 import java.security.PublicKey;
43 import java.security.SecureRandom;
44 import java.security.spec.AlgorithmParameterSpec;
45 import java.security.spec.InvalidKeySpecException;
46 import java.security.spec.MGF1ParameterSpec;
47 import java.security.spec.PKCS8EncodedKeySpec;
48 import java.security.spec.X509EncodedKeySpec;
49 import java.util.ArrayList;
50 import java.util.List;
51
52 import javax.crypto.AEADBadTagException;
53 import javax.crypto.BadPaddingException;
54 import javax.crypto.Cipher;
55 import javax.crypto.CipherSpi;
56 import javax.crypto.IllegalBlockSizeException;
57 import javax.crypto.NoSuchPaddingException;
58 import javax.crypto.SecretKey;
59 import javax.crypto.SecretKeyFactory;
60 import javax.crypto.ShortBufferException;
61 import javax.crypto.spec.OAEPParameterSpec;
62 import javax.crypto.spec.PSource;
63 import javax.crypto.spec.SecretKeySpec;
64
65 /**
66 * Base class for {@link CipherSpi} implementations of Android KeyStore backed ciphers.
67 *
68 * @hide
69 */
70 abstract class AndroidKeyStoreCipherSpiBase extends CipherSpi implements KeyStoreCryptoOperation {
71 private static final String TAG = "AndroidKeyStoreCipherSpiBase";
72 public static final String DEFAULT_MGF1_DIGEST = "SHA-1";
73
74 // Fields below are populated by Cipher.init and KeyStore.begin and should be preserved after
75 // doFinal finishes.
76 private boolean mEncrypting;
77 private int mKeymasterPurposeOverride = -1;
78 private AndroidKeyStoreKey mKey;
79 private SecureRandom mRng;
80
81 /**
82 * Object representing this operation inside keystore service. It is initialized
83 * by {@code engineInit} and is invalidated when {@code engineDoFinal} succeeds and on some
84 * error conditions in between.
85 */
86 private KeyStoreOperation mOperation;
87 /**
88 * The operation challenge is required when an operation needs user authorization.
89 * The challenge is subjected to an authenticator, e.g., Gatekeeper or a biometric
90 * authenticator, and included in the authentication token minted by this authenticator.
91 * It may be null, if the operation does not require authorization.
92 */
93 private long mOperationChallenge;
94 private KeyStoreCryptoOperationStreamer mMainDataStreamer;
95 private KeyStoreCryptoOperationStreamer mAdditionalAuthenticationDataStreamer;
96 private boolean mAdditionalAuthenticationDataStreamerClosed;
97
98 /**
99 * Encountered exception which could not be immediately thrown because it was encountered inside
100 * a method that does not throw checked exception. This exception will be thrown from
101 * {@code engineDoFinal}. Once such an exception is encountered, {@code engineUpdate} and
102 * {@code engineDoFinal} start ignoring input data.
103 */
104 private Exception mCachedException;
105
106 private Cipher mCipher;
107
108 AndroidKeyStoreCipherSpiBase() {
109 mOperation = null;
110 mEncrypting = false;
111 mKeymasterPurposeOverride = -1;
112 mKey = null;
113 mRng = null;
114 mOperationChallenge = 0;
115 mMainDataStreamer = null;
116 mAdditionalAuthenticationDataStreamer = null;
117 mAdditionalAuthenticationDataStreamerClosed = false;
118 mCachedException = null;
119 mCipher = null;
120 }
121
122 @Override
123 protected final void engineInit(int opmode, Key key, SecureRandom random)
124 throws InvalidKeyException {
125 resetAll();
126
127 // Public key operations get diverted to the default provider.
128 if (!(key instanceof AndroidKeyStorePrivateKey)
129 && (key instanceof PrivateKey || key instanceof PublicKey)) {
130 try {
131 mCipher = Cipher.getInstance(getTransform());
132 String transform = getTransform();
133
134 if ("RSA/ECB/OAEPWithSHA-224AndMGF1Padding".equals(transform)) {
135 OAEPParameterSpec spec =
136 new OAEPParameterSpec("SHA-224", "MGF1",
137 new MGF1ParameterSpec(DEFAULT_MGF1_DIGEST),
138 PSource.PSpecified.DEFAULT);
139 mCipher.init(opmode, key, spec, random);
140 } else if ("RSA/ECB/OAEPWithSHA-256AndMGF1Padding".equals(transform)) {
141 OAEPParameterSpec spec =
142 new OAEPParameterSpec("SHA-256", "MGF1",
143 new MGF1ParameterSpec(DEFAULT_MGF1_DIGEST),
144 PSource.PSpecified.DEFAULT);
145 mCipher.init(opmode, key, spec, random);
146
147 } else if ("RSA/ECB/OAEPWithSHA-384AndMGF1Padding".equals(transform)) {
148 OAEPParameterSpec spec =
149 new OAEPParameterSpec("SHA-384", "MGF1",
150 new MGF1ParameterSpec(DEFAULT_MGF1_DIGEST),
151 PSource.PSpecified.DEFAULT);
152 mCipher.init(opmode, key, spec, random);
153
154 } else if ("RSA/ECB/OAEPWithSHA-512AndMGF1Padding".equals(transform)) {
155 OAEPParameterSpec spec =
156 new OAEPParameterSpec("SHA-512", "MGF1",
157 new MGF1ParameterSpec(DEFAULT_MGF1_DIGEST),
158 PSource.PSpecified.DEFAULT);
159 mCipher.init(opmode, key, spec, random);
160 } else {
161 mCipher.init(opmode, key, random);
162 }
163 return;
164 } catch (NoSuchAlgorithmException
165 | NoSuchPaddingException
166 | InvalidAlgorithmParameterException e) {
167 throw new InvalidKeyException(e);
168 }
169 }
170
171 boolean success = false;
172 try {
173 init(opmode, key, random);
174 initAlgorithmSpecificParameters();
175 try {
176 ensureKeystoreOperationInitialized();
177 } catch (InvalidAlgorithmParameterException e) {
178 throw new InvalidKeyException(e);
179 }
180 success = true;
181 } finally {
182 if (!success) {
183 resetAll();
184 }
185 }
186 }
187
188 @Override
189 protected final void engineInit(int opmode, Key key, AlgorithmParameters params,
190 SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
191 resetAll();
192
193 // Public key operations get diverted to the default provider.
194 if (!(key instanceof AndroidKeyStorePrivateKey)
195 && (key instanceof PrivateKey || key instanceof PublicKey)) {
196 try {
197 mCipher = Cipher.getInstance(getTransform());
198 mCipher.init(opmode, key, params, random);
199 return;
200 } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
201 throw new InvalidKeyException(e);
202 }
203 }
204
205 boolean success = false;
206 try {
207 init(opmode, key, random);
208 initAlgorithmSpecificParameters(params);
209 ensureKeystoreOperationInitialized();
210 success = true;
211 } finally {
212 if (!success) {
213 resetAll();
214 }
215 }
216 }
217
218 @Override
219 protected final void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
220 SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
221 resetAll();
222
223 // Public key operations get diverted to the default provider.
224 if (!(key instanceof AndroidKeyStorePrivateKey)
225 && (key instanceof PrivateKey || key instanceof PublicKey)) {
226 try {
227 mCipher = Cipher.getInstance(getTransform());
228 mCipher.init(opmode, key, params, random);
229 return;
230 } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
231 throw new InvalidKeyException(e);
232 }
233 }
234
235 boolean success = false;
236 try {
237 init(opmode, key, random);
238 initAlgorithmSpecificParameters(params);
239 ensureKeystoreOperationInitialized();
240 success = true;
241 } finally {
242 if (!success) {
243 resetAll();
244 }
245 }
246 }
247
248 private void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
249 switch (opmode) {
250 case Cipher.ENCRYPT_MODE:
251 case Cipher.WRAP_MODE:
252 mEncrypting = true;
253 break;
254 case Cipher.DECRYPT_MODE:
255 case Cipher.UNWRAP_MODE:
256 mEncrypting = false;
257 break;
258 default:
259 throw new InvalidParameterException("Unsupported opmode: " + opmode);
260 }
261 initKey(opmode, key);
262 if (mKey == null) {
263 throw new ProviderException("initKey did not initialize the key");
264 }
265 mRng = random;
266 }
267
268 private void abortOperation() {
269 KeyStoreCryptoOperationUtils.abortOperation(mOperation);
270 mOperation = null;
271 }
272
273 /**
274 * Resets this cipher to its pristine pre-init state. This must be equivalent to obtaining a new
275 * cipher instance.
276 *
277 * <p>Subclasses storing additional state should override this method, reset the additional
278 * state, and then chain to superclass.
279 */
280 @CallSuper
281 protected void resetAll() {
282 abortOperation();
283 mEncrypting = false;
284 mKeymasterPurposeOverride = -1;
285 mKey = null;
286 mRng = null;
287 mOperationChallenge = 0;
288 mMainDataStreamer = null;
289 mAdditionalAuthenticationDataStreamer = null;
290 mAdditionalAuthenticationDataStreamerClosed = false;
291 mCachedException = null;
292 mCipher = null;
293 }
294
295 /**
296 * Resets this cipher while preserving the initialized state. This must be equivalent to
297 * rolling back the cipher's state to just after the most recent {@code engineInit} completed
298 * successfully.
299 *
300 * <p>Subclasses storing additional post-init state should override this method, reset the
301 * additional state, and then chain to superclass.
302 */
303 @CallSuper
304 protected void resetWhilePreservingInitState() {
305 abortOperation();
306 mOperationChallenge = 0;
307 mMainDataStreamer = null;
308 mAdditionalAuthenticationDataStreamer = null;
309 mAdditionalAuthenticationDataStreamerClosed = false;
310 mCachedException = null;
311 }
312
313 private void ensureKeystoreOperationInitialized() throws InvalidKeyException,
314 InvalidAlgorithmParameterException {
315 if (mMainDataStreamer != null) {
316 return;
317 }
318 if (mCachedException != null) {
319 return;
320 }
321 if (mKey == null) {
322 throw new IllegalStateException("Not initialized");
323 }
324
325 List<KeyParameter> parameters = new ArrayList<>();
326 addAlgorithmSpecificParametersToBegin(parameters);
327
328 int purpose;
329 if (mKeymasterPurposeOverride != -1) {
330 purpose = mKeymasterPurposeOverride;
331 } else {
332 purpose = mEncrypting
333 ? KeymasterDefs.KM_PURPOSE_ENCRYPT : KeymasterDefs.KM_PURPOSE_DECRYPT;
334 }
335
336 parameters.add(KeyStore2ParameterUtils.makeEnum(KeymasterDefs.KM_TAG_PURPOSE, purpose));
337
338 try {
339 mOperation = mKey.getSecurityLevel().createOperation(
340 mKey.getKeyIdDescriptor(),
341 parameters
342 );
343 } catch (KeyStoreException keyStoreException) {
344 GeneralSecurityException e = KeyStoreCryptoOperationUtils.getExceptionForCipherInit(
345 mKey, keyStoreException);
346 if (e != null) {
347 if (e instanceof InvalidKeyException) {
348 throw (InvalidKeyException) e;
349 } else if (e instanceof InvalidAlgorithmParameterException) {
350 throw (InvalidAlgorithmParameterException) e;
351 } else {
352 throw new ProviderException("Unexpected exception type", e);
353 }
354 }
355 }
356
357 // Now we check if we got an operation challenge. This indicates that user authorization
358 // is required. And if we got a challenge we check if the authorization can possibly
359 // succeed.
360 mOperationChallenge = KeyStoreCryptoOperationUtils.getOrMakeOperationChallenge(
361 mOperation, mKey);
362
363 loadAlgorithmSpecificParametersFromBeginResult(mOperation.getParameters());
364 mMainDataStreamer = createMainDataStreamer(mOperation);
365 mAdditionalAuthenticationDataStreamer =
366 createAdditionalAuthenticationDataStreamer(mOperation);
367 mAdditionalAuthenticationDataStreamerClosed = false;
368 }
369
370 /**
371 * Creates a streamer which sends plaintext/ciphertext into the provided KeyStore and receives
372 * the corresponding ciphertext/plaintext from the KeyStore.
373 *
374 * <p>This implementation returns a working streamer.
375 */
376 @NonNull
377 protected KeyStoreCryptoOperationStreamer createMainDataStreamer(
378 KeyStoreOperation operation) {
379 return new KeyStoreCryptoOperationChunkedStreamer(
380 new KeyStoreCryptoOperationChunkedStreamer.MainDataStream(
381 operation), 0);
382 }
383
384 /**
385 * Creates a streamer which sends Additional Authentication Data (AAD) into the KeyStore.
386 *
387 * <p>This implementation returns {@code null}.
388 *
389 * @return stream or {@code null} if AAD is not supported by this cipher.
390 */
391 @Nullable
392 protected KeyStoreCryptoOperationStreamer createAdditionalAuthenticationDataStreamer(
393 @SuppressWarnings("unused") KeyStoreOperation operation) {
394 return null;
395 }
396
397 @Override
398 protected final byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
399 if (mCipher != null) {
400 return mCipher.update(input, inputOffset, inputLen);
401 }
402
403 if (mCachedException != null) {
404 return null;
405 }
406 try {
407 ensureKeystoreOperationInitialized();
408 } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
409 mCachedException = e;
410 return null;
411 }
412
413 if (inputLen == 0) {
414 return null;
415 }
416
417 byte[] output;
418 try {
419 flushAAD();
420 output = mMainDataStreamer.update(input, inputOffset, inputLen);
421 } catch (KeyStoreException e) {
422 mCachedException = e;
423 return null;
424 }
425
426 if (output.length == 0) {
427 return null;
428 }
429
430 return output;
431 }
432
433 private void flushAAD() throws KeyStoreException {
434 if ((mAdditionalAuthenticationDataStreamer != null)
435 && (!mAdditionalAuthenticationDataStreamerClosed)) {
436 byte[] output;
437 try {
438 output = mAdditionalAuthenticationDataStreamer.doFinal(
439 EmptyArray.BYTE, 0, 0,
440 null); // no signature
441 } finally {
442 mAdditionalAuthenticationDataStreamerClosed = true;
443 }
444 if ((output != null) && (output.length > 0)) {
445 throw new ProviderException(
446 "AAD update unexpectedly returned data: " + output.length + " bytes");
447 }
448 }
449 }
450
451 @Override
452 protected final int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output,
453 int outputOffset) throws ShortBufferException {
454 if (mCipher != null) {
455 return mCipher.update(input, inputOffset, inputLen, output);
456 }
457 byte[] outputCopy = engineUpdate(input, inputOffset, inputLen);
458 if (outputCopy == null) {
459 return 0;
460 }
461 int outputAvailable = output.length - outputOffset;
462 if (outputCopy.length > outputAvailable) {
463 throw new ShortBufferException("Output buffer too short. Produced: "
464 + outputCopy.length + ", available: " + outputAvailable);
465 }
466 System.arraycopy(outputCopy, 0, output, outputOffset, outputCopy.length);
467 return outputCopy.length;
468 }
469
470 @Override
471 protected final int engineUpdate(ByteBuffer input, ByteBuffer output)
472 throws ShortBufferException {
473 if (mCipher != null) {
474 return mCipher.update(input, output);
475 }
476
477 if (input == null) {
478 throw new NullPointerException("input == null");
479 }
480 if (output == null) {
481 throw new NullPointerException("output == null");
482 }
483
484 int inputSize = input.remaining();
485 byte[] outputArray;
486 if (input.hasArray()) {
487 outputArray =
488 engineUpdate(
489 input.array(), input.arrayOffset() + input.position(), inputSize);
490 input.position(input.position() + inputSize);
491 } else {
492 byte[] inputArray = new byte[inputSize];
493 input.get(inputArray);
494 outputArray = engineUpdate(inputArray, 0, inputSize);
495 }
496
497 int outputSize = (outputArray != null) ? outputArray.length : 0;
498 if (outputSize > 0) {
499 int outputBufferAvailable = output.remaining();
500 try {
501 output.put(outputArray);
502 } catch (BufferOverflowException e) {
503 throw new ShortBufferException(
504 "Output buffer too small. Produced: " + outputSize + ", available: "
505 + outputBufferAvailable);
506 }
507 }
508 return outputSize;
509 }
510
511 @Override
512 protected final void engineUpdateAAD(byte[] input, int inputOffset, int inputLen) {
513 if (mCipher != null) {
514 mCipher.updateAAD(input, inputOffset, inputLen);
515 return;
516 }
517
518 if (mCachedException != null) {
519 return;
520 }
521
522 try {
523 ensureKeystoreOperationInitialized();
524 } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
525 mCachedException = e;
526 return;
527 }
528
529 if (mAdditionalAuthenticationDataStreamerClosed) {
530 throw new IllegalStateException(
531 "AAD can only be provided before Cipher.update is invoked");
532 }
533
534 if (mAdditionalAuthenticationDataStreamer == null) {
535 throw new IllegalStateException("This cipher does not support AAD");
536 }
537
538 byte[] output;
539 try {
540 output = mAdditionalAuthenticationDataStreamer.update(input, inputOffset, inputLen);
541 } catch (KeyStoreException e) {
542 mCachedException = e;
543 return;
544 }
545
546 if ((output != null) && (output.length > 0)) {
547 throw new ProviderException("AAD update unexpectedly produced output: "
548 + output.length + " bytes");
549 }
550 }
551
552 @Override
553 protected final void engineUpdateAAD(ByteBuffer src) {
554 if (mCipher != null) {
555 mCipher.updateAAD(src);
556 return;
557 }
558
559 if (src == null) {
560 throw new IllegalArgumentException("src == null");
561 }
562 if (!src.hasRemaining()) {
563 return;
564 }
565
566 byte[] input;
567 int inputOffset;
568 int inputLen;
569 if (src.hasArray()) {
570 input = src.array();
571 inputOffset = src.arrayOffset() + src.position();
572 inputLen = src.remaining();
573 src.position(src.limit());
574 } else {
575 input = new byte[src.remaining()];
576 inputOffset = 0;
577 inputLen = input.length;
578 src.get(input);
579 }
580 engineUpdateAAD(input, inputOffset, inputLen);
581 }
582
583 @Override
584 protected final byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
585 throws IllegalBlockSizeException, BadPaddingException {
586 if (mCipher != null) {
587 if (input == null && inputLen == 0) {
588 return mCipher.doFinal();
589 } else {
590 return mCipher.doFinal(input, inputOffset, inputLen);
591 }
592 }
593
594 if (mCachedException != null) {
595 throw (IllegalBlockSizeException)
596 new IllegalBlockSizeException().initCause(mCachedException);
597 }
598
599 try {
600 ensureKeystoreOperationInitialized();
601 } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
602 throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
603 }
604
605 byte[] output;
606 try {
607 flushAAD();
608 output = mMainDataStreamer.doFinal(
609 input, inputOffset, inputLen,
610 null); // no signature involved
611 } catch (KeyStoreException e) {
612 switch (e.getErrorCode()) {
613 case KeymasterDefs.KM_ERROR_INVALID_ARGUMENT:
614 throw (BadPaddingException) new BadPaddingException().initCause(e);
615 case KeymasterDefs.KM_ERROR_VERIFICATION_FAILED:
616 throw (AEADBadTagException) new AEADBadTagException().initCause(e);
617 default:
618 throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
619 }
620 }
621
622 resetWhilePreservingInitState();
623 return output;
624 }
625
626 @Override
627 protected final int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
628 int outputOffset) throws ShortBufferException, IllegalBlockSizeException,
629 BadPaddingException {
630 if (mCipher != null) {
631 return mCipher.doFinal(input, inputOffset, inputLen, output);
632 }
633
634 byte[] outputCopy = engineDoFinal(input, inputOffset, inputLen);
635 if (outputCopy == null) {
636 return 0;
637 }
638 int outputAvailable = output.length - outputOffset;
639 if (outputCopy.length > outputAvailable) {
640 throw new ShortBufferException("Output buffer too short. Produced: "
641 + outputCopy.length + ", available: " + outputAvailable);
642 }
643 System.arraycopy(outputCopy, 0, output, outputOffset, outputCopy.length);
644 return outputCopy.length;
645 }
646
647 @Override
648 protected final int engineDoFinal(ByteBuffer input, ByteBuffer output)
649 throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
650 if (mCipher != null) {
651 return mCipher.doFinal(input, output);
652 }
653
654 if (input == null) {
655 throw new NullPointerException("input == null");
656 }
657 if (output == null) {
658 throw new NullPointerException("output == null");
659 }
660
661 int inputSize = input.remaining();
662 byte[] outputArray;
663 if (input.hasArray()) {
664 outputArray =
665 engineDoFinal(
666 input.array(), input.arrayOffset() + input.position(), inputSize);
667 input.position(input.position() + inputSize);
668 } else {
669 byte[] inputArray = new byte[inputSize];
670 input.get(inputArray);
671 outputArray = engineDoFinal(inputArray, 0, inputSize);
672 }
673
674 int outputSize = (outputArray != null) ? outputArray.length : 0;
675 if (outputSize > 0) {
676 int outputBufferAvailable = output.remaining();
677 try {
678 output.put(outputArray);
679 } catch (BufferOverflowException e) {
680 throw new ShortBufferException(
681 "Output buffer too small. Produced: " + outputSize + ", available: "
682 + outputBufferAvailable);
683 }
684 }
685 return outputSize;
686 }
687
688 @Override
689 protected final byte[] engineWrap(Key key)
690 throws IllegalBlockSizeException, InvalidKeyException {
691 if (mCipher != null) {
692 return mCipher.wrap(key);
693 }
694
695 if (mKey == null) {
696 throw new IllegalStateException("Not initilized");
697 }
698
699 if (!isEncrypting()) {
700 throw new IllegalStateException(
701 "Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
702 }
703
704 if (key == null) {
705 throw new NullPointerException("key == null");
706 }
707 byte[] encoded = null;
708 if (key instanceof SecretKey) {
709 if ("RAW".equalsIgnoreCase(key.getFormat())) {
710 encoded = key.getEncoded();
711 }
712 if (encoded == null) {
713 try {
714 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key.getAlgorithm());
715 SecretKeySpec spec =
716 (SecretKeySpec) keyFactory.getKeySpec(
717 (SecretKey) key, SecretKeySpec.class);
718 encoded = spec.getEncoded();
719 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
720 throw new InvalidKeyException(
721 "Failed to wrap key because it does not export its key material",
722 e);
723 }
724 }
725 } else if (key instanceof PrivateKey) {
726 if ("PKCS8".equalsIgnoreCase(key.getFormat())) {
727 encoded = key.getEncoded();
728 }
729 if (encoded == null) {
730 try {
731 KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
732 PKCS8EncodedKeySpec spec =
733 keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
734 encoded = spec.getEncoded();
735 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
736 throw new InvalidKeyException(
737 "Failed to wrap key because it does not export its key material",
738 e);
739 }
740 }
741 } else if (key instanceof PublicKey) {
742 if ("X.509".equalsIgnoreCase(key.getFormat())) {
743 encoded = key.getEncoded();
744 }
745 if (encoded == null) {
746 try {
747 KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
748 X509EncodedKeySpec spec =
749 keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
750 encoded = spec.getEncoded();
751 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
752 throw new InvalidKeyException(
753 "Failed to wrap key because it does not export its key material",
754 e);
755 }
756 }
757 } else {
758 throw new InvalidKeyException("Unsupported key type: " + key.getClass().getName());
759 }
760
761 if (encoded == null) {
762 throw new InvalidKeyException(
763 "Failed to wrap key because it does not export its key material");
764 }
765
766 try {
767 return engineDoFinal(encoded, 0, encoded.length);
768 } catch (BadPaddingException e) {
769 throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
770 }
771 }
772
773 @Override
774 protected final Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
775 int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException {
776 if (mCipher != null) {
777 return mCipher.unwrap(wrappedKey, wrappedKeyAlgorithm, wrappedKeyType);
778 }
779
780 if (mKey == null) {
781 throw new IllegalStateException("Not initilized");
782 }
783
784 if (isEncrypting()) {
785 throw new IllegalStateException(
786 "Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
787 }
788
789 if (wrappedKey == null) {
790 throw new NullPointerException("wrappedKey == null");
791 }
792
793 byte[] encoded;
794 try {
795 encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
796 } catch (IllegalBlockSizeException | BadPaddingException e) {
797 throw new InvalidKeyException("Failed to unwrap key", e);
798 }
799
800 switch (wrappedKeyType) {
801 case Cipher.SECRET_KEY:
802 {
803 return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
804 // break;
805 }
806 case Cipher.PRIVATE_KEY:
807 {
808 KeyFactory keyFactory = KeyFactory.getInstance(wrappedKeyAlgorithm);
809 try {
810 return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encoded));
811 } catch (InvalidKeySpecException e) {
812 throw new InvalidKeyException(
813 "Failed to create private key from its PKCS#8 encoded form", e);
814 }
815 // break;
816 }
817 case Cipher.PUBLIC_KEY:
818 {
819 KeyFactory keyFactory = KeyFactory.getInstance(wrappedKeyAlgorithm);
820 try {
821 return keyFactory.generatePublic(new X509EncodedKeySpec(encoded));
822 } catch (InvalidKeySpecException e) {
823 throw new InvalidKeyException(
824 "Failed to create public key from its X.509 encoded form", e);
825 }
826 // break;
827 }
828 default:
829 throw new InvalidParameterException(
830 "Unsupported wrappedKeyType: " + wrappedKeyType);
831 }
832 }
833
834 @Override
835 protected final void engineSetMode(String mode) throws NoSuchAlgorithmException {
836 // This should never be invoked because all algorithms registered with the AndroidKeyStore
837 // provide explicitly specify block mode.
838 throw new UnsupportedOperationException();
839 }
840
841 @Override
842 protected final void engineSetPadding(String arg0) throws NoSuchPaddingException {
843 // This should never be invoked because all algorithms registered with the AndroidKeyStore
844 // provide explicitly specify padding mode.
845 throw new UnsupportedOperationException();
846 }
847
848 @Override
849 protected final int engineGetKeySize(Key key) throws InvalidKeyException {
850 throw new UnsupportedOperationException();
851 }
852
853 @CallSuper
854 @Override
855 public void finalize() throws Throwable {
856 try {
857 abortOperation();
858 } finally {
859 super.finalize();
860 }
861 }
862
863 @Override
864 public final long getOperationHandle() {
865 return mOperationChallenge;
866 }
867
868 protected final void setKey(@NonNull AndroidKeyStoreKey key) {
869 mKey = key;
870 }
871
872 /**
873 * Overrides the default purpose/type of the crypto operation.
874 */
875 protected final void setKeymasterPurposeOverride(int keymasterPurpose) {
876 mKeymasterPurposeOverride = keymasterPurpose;
877 }
878
879 protected final int getKeymasterPurposeOverride() {
880 return mKeymasterPurposeOverride;
881 }
882
883 /**
884 * Returns {@code true} if this cipher is initialized for encryption, {@code false} if this
885 * cipher is initialized for decryption.
886 */
887 protected final boolean isEncrypting() {
888 return mEncrypting;
889 }
890
891 protected final long getConsumedInputSizeBytes() {
892 if (mMainDataStreamer == null) {
893 throw new IllegalStateException("Not initialized");
894 }
895 return mMainDataStreamer.getConsumedInputSizeBytes();
896 }
897
898 protected final long getProducedOutputSizeBytes() {
899 if (mMainDataStreamer == null) {
900 throw new IllegalStateException("Not initialized");
901 }
902 return mMainDataStreamer.getProducedOutputSizeBytes();
903 }
904
905 static String opmodeToString(int opmode) {
906 switch (opmode) {
907 case Cipher.ENCRYPT_MODE:
908 return "ENCRYPT_MODE";
909 case Cipher.DECRYPT_MODE:
910 return "DECRYPT_MODE";
911 case Cipher.WRAP_MODE:
912 return "WRAP_MODE";
913 case Cipher.UNWRAP_MODE:
914 return "UNWRAP_MODE";
915 default:
916 return String.valueOf(opmode);
917 }
918 }
919
920 // The methods below need to be implemented by subclasses.
921
922 /**
923 * Initializes this cipher with the provided key.
924 *
925 * @throws InvalidKeyException if the {@code key} is not suitable for this cipher in the
926 * specified {@code opmode}.
927 *
928 * @see #setKey(AndroidKeyStoreKey)
929 */
930 protected abstract void initKey(int opmode, @Nullable Key key) throws InvalidKeyException;
931
932 /**
933 * Returns algorithm-specific parameters used by this cipher or {@code null} if no
934 * algorithm-specific parameters are used.
935 */
936 @Nullable
937 @Override
938 protected abstract AlgorithmParameters engineGetParameters();
939
940 /**
941 * Invoked by {@code engineInit} to initialize algorithm-specific parameters when no additional
942 * initialization parameters were provided.
943 *
944 * @throws InvalidKeyException if this cipher cannot be configured based purely on the provided
945 * key and needs additional parameters to be provided to {@code Cipher.init}.
946 */
947 protected abstract void initAlgorithmSpecificParameters() throws InvalidKeyException;
948
949 /**
950 * Invoked by {@code engineInit} to initialize algorithm-specific parameters when additional
951 * parameters were provided.
952 *
953 * @param params additional algorithm parameters or {@code null} if not specified.
954 *
955 * @throws InvalidAlgorithmParameterException if there is insufficient information to configure
956 * this cipher or if the provided parameters are not suitable for this cipher.
957 */
958 protected abstract void initAlgorithmSpecificParameters(
959 @Nullable AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException;
960
961 /**
962 * Invoked by {@code engineInit} to initialize algorithm-specific parameters when additional
963 * parameters were provided.
964 *
965 * @param params additional algorithm parameters or {@code null} if not specified.
966 *
967 * @throws InvalidAlgorithmParameterException if there is insufficient information to configure
968 * this cipher or if the provided parameters are not suitable for this cipher.
969 */
970 protected abstract void initAlgorithmSpecificParameters(@Nullable AlgorithmParameters params)
971 throws InvalidAlgorithmParameterException;
972
973 /**
974 * Returns the amount of additional entropy (in bytes) to be provided to the KeyStore's
975 * {@code begin} operation. This amount of entropy is typically what's consumed to generate
976 * random parameters, such as IV.
977 *
978 * <p>For decryption, the return value should be {@code 0} because decryption should not be
979 * consuming any entropy. For encryption, the value combined with
980 * {@link #getAdditionalEntropyAmountForFinish()} should match (or exceed) the amount of Shannon
981 * entropy of the ciphertext produced by this cipher assuming the key, the plaintext, and all
982 * explicitly provided parameters to {@code Cipher.init} are known. For example, for AES CBC
983 * encryption with an explicitly provided IV the return value should be {@code 0}, whereas for
984 * the case where IV is generated by the KeyStore's {@code begin} operation it should be
985 * {@code 16}.
986 */
987 protected abstract int getAdditionalEntropyAmountForBegin();
988
989 /**
990 * Returns the amount of additional entropy (in bytes) to be provided to the KeyStore's
991 * {@code finish} operation. This amount of entropy is typically what's consumed by encryption
992 * padding scheme.
993 *
994 * <p>For decryption, the return value should be {@code 0} because decryption should not be
995 * consuming any entropy. For encryption, the value combined with
996 * {@link #getAdditionalEntropyAmountForBegin()} should match (or exceed) the amount of Shannon
997 * entropy of the ciphertext produced by this cipher assuming the key, the plaintext, and all
998 * explicitly provided parameters to {@code Cipher.init} are known. For example, for RSA with
999 * OAEP the return value should be the size of the OAEP hash output. For RSA with PKCS#1 padding
1000 * the return value should be the size of the padding string or could be raised (for simplicity)
1001 * to the size of the modulus.
1002 */
1003 protected abstract int getAdditionalEntropyAmountForFinish();
1004
1005 /**
1006 * Invoked to add algorithm-specific parameters for the KeyStore's {@code begin} operation.
1007 *
1008 * @param parameters keystore/keymaster arguments to be populated with algorithm-specific
1009 * parameters.
1010 */
1011 protected abstract void addAlgorithmSpecificParametersToBegin(
1012 @NonNull List<KeyParameter> parameters);
1013
1014 /**
1015 * Invoked to obtain algorithm-specific parameters from the result of the KeyStore's
1016 * {@code begin} operation.
1017 *
1018 * <p>Some parameters, such as IV, are not required to be provided to {@code Cipher.init}. Such
1019 * parameters, if not provided, must be generated by KeyStore and returned to the user of
1020 * {@code Cipher} and potentially reused after {@code doFinal}.
1021 *
1022 * @param parameters keystore/keymaster arguments returned by KeyStore {@code createOperation}.
1023 */
1024 protected abstract void loadAlgorithmSpecificParametersFromBeginResult(
1025 KeyParameter[] parameters);
1026
1027 protected abstract String getTransform();
1028 }