Debian Codegraph @

keystore/java/android/security/keystore2/AndroidKeyStoreRSACipherSpi.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.NonNull;
20 import android.annotation.Nullable;
21 import android.hardware.security.keymint.KeyParameter;
22 import android.security.keymaster.KeymasterDefs;
23 import android.security.keystore.KeyProperties;
24 import android.system.keystore2.Authorization;
25
26 import java.security.AlgorithmParameters;
27 import java.security.InvalidAlgorithmParameterException;
28 import java.security.InvalidKeyException;
29 import java.security.Key;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.PrivateKey;
32 import java.security.ProviderException;
33 import java.security.spec.AlgorithmParameterSpec;
34 import java.security.spec.InvalidParameterSpecException;
35 import java.security.spec.MGF1ParameterSpec;
36 import java.util.List;
37
38 import javax.crypto.Cipher;
39 import javax.crypto.CipherSpi;
40 import javax.crypto.spec.OAEPParameterSpec;
41 import javax.crypto.spec.PSource;
42
43 /**
44 * Base class for {@link CipherSpi} providing Android KeyStore backed RSA encryption/decryption.
45 *
46 * @hide
47 */
48 abstract class AndroidKeyStoreRSACipherSpi extends AndroidKeyStoreCipherSpiBase {
49
50 /**
51 * Raw RSA cipher without any padding.
52 */
53 public static final class NoPadding extends AndroidKeyStoreRSACipherSpi {
54 public NoPadding() {
55 super(KeymasterDefs.KM_PAD_NONE);
56 }
57
58 @Override
59 protected boolean adjustConfigForEncryptingWithPrivateKey() {
60 // RSA encryption with no padding using private key is a way to implement raw RSA
61 // signatures which JCA does not expose via Signature. We thus have to support this.
62 setKeymasterPurposeOverride(KeymasterDefs.KM_PURPOSE_SIGN);
63 return true;
64 }
65
66 @Override
67 protected void initAlgorithmSpecificParameters() throws InvalidKeyException {}
68
69 @Override
70 protected void initAlgorithmSpecificParameters(@Nullable AlgorithmParameterSpec params)
71 throws InvalidAlgorithmParameterException {
72 if (params != null) {
73 throw new InvalidAlgorithmParameterException(
74 "Unexpected parameters: " + params + ". No parameters supported");
75 }
76 }
77
78 @Override
79 protected void initAlgorithmSpecificParameters(@Nullable AlgorithmParameters params)
80 throws InvalidAlgorithmParameterException {
81
82 if (params != null) {
83 throw new InvalidAlgorithmParameterException(
84 "Unexpected parameters: " + params + ". No parameters supported");
85 }
86 }
87
88 @Override
89 protected AlgorithmParameters engineGetParameters() {
90 return null;
91 }
92
93 @Override
94 protected final int getAdditionalEntropyAmountForBegin() {
95 return 0;
96 }
97
98 @Override
99 protected final int getAdditionalEntropyAmountForFinish() {
100 return 0;
101 }
102 }
103
104 /**
105 * RSA cipher with PKCS#1 v1.5 encryption padding.
106 */
107 public static final class PKCS1Padding extends AndroidKeyStoreRSACipherSpi {
108 public PKCS1Padding() {
109 super(KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
110 }
111
112 @Override
113 protected boolean adjustConfigForEncryptingWithPrivateKey() {
114 // RSA encryption with PCKS#1 padding using private key is a way to implement RSA
115 // signatures with PKCS#1 padding. We have to support this for legacy reasons.
116 setKeymasterPurposeOverride(KeymasterDefs.KM_PURPOSE_SIGN);
117 setKeymasterPaddingOverride(KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN);
118 return true;
119 }
120
121 @Override
122 protected void initAlgorithmSpecificParameters() throws InvalidKeyException {}
123
124 @Override
125 protected void initAlgorithmSpecificParameters(@Nullable AlgorithmParameterSpec params)
126 throws InvalidAlgorithmParameterException {
127 if (params != null) {
128 throw new InvalidAlgorithmParameterException(
129 "Unexpected parameters: " + params + ". No parameters supported");
130 }
131 }
132
133 @Override
134 protected void initAlgorithmSpecificParameters(@Nullable AlgorithmParameters params)
135 throws InvalidAlgorithmParameterException {
136
137 if (params != null) {
138 throw new InvalidAlgorithmParameterException(
139 "Unexpected parameters: " + params + ". No parameters supported");
140 }
141 }
142
143 @Override
144 protected AlgorithmParameters engineGetParameters() {
145 return null;
146 }
147
148 @Override
149 protected final int getAdditionalEntropyAmountForBegin() {
150 return 0;
151 }
152
153 @Override
154 protected final int getAdditionalEntropyAmountForFinish() {
155 return (isEncrypting()) ? getModulusSizeBytes() : 0;
156 }
157 }
158
159 /**
160 * RSA cipher with OAEP encryption padding.
161 */
162 abstract static class OAEPWithMGF1Padding extends AndroidKeyStoreRSACipherSpi {
163
164 private static final String MGF_ALGORITHM_MGF1 = "MGF1";
165
166 private int mKeymasterDigest = -1;
167 private int mDigestOutputSizeBytes;
168 private int mKeymasterMgf1Digest = KeymasterDefs.KM_DIGEST_SHA1; // Default MGF1 digest
169
170 OAEPWithMGF1Padding(int keymasterDigest) {
171 super(KeymasterDefs.KM_PAD_RSA_OAEP);
172 mKeymasterDigest = keymasterDigest;
173 mDigestOutputSizeBytes =
174 (KeymasterUtils.getDigestOutputSizeBits(keymasterDigest) + 7) / 8;
175 }
176
177 @Override
178 protected final void initAlgorithmSpecificParameters() throws InvalidKeyException {}
179
180 @Override
181 protected final void initAlgorithmSpecificParameters(
182 @Nullable AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException {
183 if (params == null) {
184 return;
185 }
186
187 if (!(params instanceof OAEPParameterSpec)) {
188 throw new InvalidAlgorithmParameterException(
189 "Unsupported parameter spec: " + params
190 + ". Only OAEPParameterSpec supported");
191 }
192 OAEPParameterSpec spec = (OAEPParameterSpec) params;
193 if (!MGF_ALGORITHM_MGF1.equalsIgnoreCase(spec.getMGFAlgorithm())) {
194 throw new InvalidAlgorithmParameterException(
195 "Unsupported MGF: " + spec.getMGFAlgorithm()
196 + ". Only " + MGF_ALGORITHM_MGF1 + " supported");
197 }
198 String jcaDigest = spec.getDigestAlgorithm();
199 int keymasterDigest;
200 try {
201 keymasterDigest = KeyProperties.Digest.toKeymaster(jcaDigest);
202 } catch (IllegalArgumentException e) {
203 throw new InvalidAlgorithmParameterException(
204 "Unsupported digest: " + jcaDigest, e);
205 }
206 switch (keymasterDigest) {
207 case KeymasterDefs.KM_DIGEST_SHA1:
208 case KeymasterDefs.KM_DIGEST_SHA_2_224:
209 case KeymasterDefs.KM_DIGEST_SHA_2_256:
210 case KeymasterDefs.KM_DIGEST_SHA_2_384:
211 case KeymasterDefs.KM_DIGEST_SHA_2_512:
212 // Permitted.
213 break;
214 default:
215 throw new InvalidAlgorithmParameterException(
216 "Unsupported digest: " + jcaDigest);
217 }
218 AlgorithmParameterSpec mgfParams = spec.getMGFParameters();
219 if (mgfParams == null) {
220 throw new InvalidAlgorithmParameterException("MGF parameters must be provided");
221 }
222 // Check whether MGF parameters match the OAEPParameterSpec
223 if (!(mgfParams instanceof MGF1ParameterSpec)) {
224 throw new InvalidAlgorithmParameterException("Unsupported MGF parameters"
225 + ": " + mgfParams + ". Only MGF1ParameterSpec supported");
226 }
227 MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec) mgfParams;
228 String mgf1JcaDigest = mgfSpec.getDigestAlgorithm();
229 PSource pSource = spec.getPSource();
230 if (!(pSource instanceof PSource.PSpecified)) {
231 throw new InvalidAlgorithmParameterException(
232 "Unsupported source of encoding input P: " + pSource
233 + ". Only pSpecifiedEmpty (PSource.PSpecified.DEFAULT) supported");
234 }
235 PSource.PSpecified pSourceSpecified = (PSource.PSpecified) pSource;
236 byte[] pSourceValue = pSourceSpecified.getValue();
237 if ((pSourceValue != null) && (pSourceValue.length > 0)) {
238 throw new InvalidAlgorithmParameterException(
239 "Unsupported source of encoding input P: " + pSource
240 + ". Only pSpecifiedEmpty (PSource.PSpecified.DEFAULT) supported");
241 }
242 mKeymasterDigest = keymasterDigest;
243 mKeymasterMgf1Digest = KeyProperties.Digest.toKeymaster(mgf1JcaDigest);
244 mDigestOutputSizeBytes =
245 (KeymasterUtils.getDigestOutputSizeBits(keymasterDigest) + 7) / 8;
246 }
247
248 @Override
249 protected final void initAlgorithmSpecificParameters(@Nullable AlgorithmParameters params)
250 throws InvalidAlgorithmParameterException {
251 if (params == null) {
252 return;
253 }
254
255 OAEPParameterSpec spec;
256 try {
257 spec = params.getParameterSpec(OAEPParameterSpec.class);
258 } catch (InvalidParameterSpecException e) {
259 throw new InvalidAlgorithmParameterException("OAEP parameters required"
260 + ", but not found in parameters: " + params, e);
261 }
262 if (spec == null) {
263 throw new InvalidAlgorithmParameterException("OAEP parameters required"
264 + ", but not provided in parameters: " + params);
265 }
266 initAlgorithmSpecificParameters(spec);
267 }
268
269 @Override
270 protected final AlgorithmParameters engineGetParameters() {
271 OAEPParameterSpec spec =
272 new OAEPParameterSpec(
273 KeyProperties.Digest.fromKeymaster(mKeymasterDigest),
274 MGF_ALGORITHM_MGF1,
275 KeyProperties.Digest.fromKeymasterToMGF1ParameterSpec(mKeymasterMgf1Digest),
276 PSource.PSpecified.DEFAULT);
277 try {
278 AlgorithmParameters params = AlgorithmParameters.getInstance("OAEP");
279 params.init(spec);
280 return params;
281 } catch (NoSuchAlgorithmException e) {
282 throw new ProviderException(
283 "Failed to obtain OAEP AlgorithmParameters", e);
284 } catch (InvalidParameterSpecException e) {
285 throw new ProviderException(
286 "Failed to initialize OAEP AlgorithmParameters with an IV",
287 e);
288 }
289 }
290
291 @Override
292 protected final void addAlgorithmSpecificParametersToBegin(
293 @NonNull List<KeyParameter> parameters) {
294 super.addAlgorithmSpecificParametersToBegin(parameters);
295 parameters.add(KeyStore2ParameterUtils.makeEnum(
296 KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigest
297 ));
298 parameters.add(KeyStore2ParameterUtils.makeEnum(
299 KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST, mKeymasterMgf1Digest
300 ));
301 }
302
303 @Override
304 protected final void loadAlgorithmSpecificParametersFromBeginResult(
305 KeyParameter[] parameters) {
306 super.loadAlgorithmSpecificParametersFromBeginResult(parameters);
307 }
308
309 @Override
310 protected final int getAdditionalEntropyAmountForBegin() {
311 return 0;
312 }
313
314 @Override
315 protected final int getAdditionalEntropyAmountForFinish() {
316 return (isEncrypting()) ? mDigestOutputSizeBytes : 0;
317 }
318
319 @Override
320 protected final String getTransform() {
321 switch (mKeymasterDigest) {
322 case KeymasterDefs.KM_DIGEST_SHA1:
323 return "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";
324 case KeymasterDefs.KM_DIGEST_SHA_2_224:
325 return "RSA/ECB/OAEPWithSHA-224AndMGF1Padding";
326 case KeymasterDefs.KM_DIGEST_SHA_2_256:
327 return "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
328 case KeymasterDefs.KM_DIGEST_SHA_2_384:
329 return "RSA/ECB/OAEPWithSHA-384AndMGF1Padding";
330 case KeymasterDefs.KM_DIGEST_SHA_2_512:
331 return "RSA/ECB/OAEPWithSHA-512AndMGF1Padding";
332 default:
333 return "RSA/ECB/OAEPPadding";
334 }
335 }
336
337 }
338
339 public static class OAEPWithSHA1AndMGF1Padding extends OAEPWithMGF1Padding {
340 public OAEPWithSHA1AndMGF1Padding() {
341 super(KeymasterDefs.KM_DIGEST_SHA1);
342 }
343 }
344
345 public static class OAEPWithSHA224AndMGF1Padding extends OAEPWithMGF1Padding {
346 public OAEPWithSHA224AndMGF1Padding() {
347 super(KeymasterDefs.KM_DIGEST_SHA_2_224);
348 }
349 }
350
351 public static class OAEPWithSHA256AndMGF1Padding extends OAEPWithMGF1Padding {
352 public OAEPWithSHA256AndMGF1Padding() {
353 super(KeymasterDefs.KM_DIGEST_SHA_2_256);
354 }
355 }
356
357 public static class OAEPWithSHA384AndMGF1Padding extends OAEPWithMGF1Padding {
358 public OAEPWithSHA384AndMGF1Padding() {
359 super(KeymasterDefs.KM_DIGEST_SHA_2_384);
360 }
361 }
362
363 public static class OAEPWithSHA512AndMGF1Padding extends OAEPWithMGF1Padding {
364 public OAEPWithSHA512AndMGF1Padding() {
365 super(KeymasterDefs.KM_DIGEST_SHA_2_512);
366 }
367 }
368
369 private final int mKeymasterPadding;
370 private int mKeymasterPaddingOverride;
371
372 private int mModulusSizeBytes = -1;
373
374 AndroidKeyStoreRSACipherSpi(int keymasterPadding) {
375 mKeymasterPadding = keymasterPadding;
376 }
377
378 @Override
379 protected String getTransform() {
380 return "RSA/ECB/" + KeyProperties.EncryptionPadding.fromKeymaster(mKeymasterPadding);
381 }
382
383 @Override
384 protected final void initKey(int opmode, Key key) throws InvalidKeyException {
385 if (key == null) {
386 throw new InvalidKeyException("Unsupported key: null");
387 }
388 if (!KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(key.getAlgorithm())) {
389 throw new InvalidKeyException("Unsupported key algorithm: " + key.getAlgorithm()
390 + ". Only " + KeyProperties.KEY_ALGORITHM_RSA + " supported");
391 }
392 AndroidKeyStoreKey keystoreKey;
393 if (key instanceof AndroidKeyStorePrivateKey) {
394 keystoreKey = (AndroidKeyStoreKey) key;
395 } else if (key instanceof AndroidKeyStorePublicKey) {
396 keystoreKey = (AndroidKeyStoreKey) key;
397 } else {
398 throw new InvalidKeyException("Unsupported key type: " + key);
399 }
400
401 if (keystoreKey instanceof PrivateKey) {
402 // Private key
403 switch (opmode) {
404 case Cipher.DECRYPT_MODE:
405 case Cipher.UNWRAP_MODE:
406 // Permitted
407 break;
408 case Cipher.ENCRYPT_MODE:
409 case Cipher.WRAP_MODE:
410 if (!adjustConfigForEncryptingWithPrivateKey()) {
411 throw new InvalidKeyException(
412 "RSA private keys cannot be used with " + opmodeToString(opmode)
413 + " and padding "
414 + KeyProperties.EncryptionPadding.fromKeymaster(mKeymasterPadding)
415 + ". Only RSA public keys supported for this mode");
416 }
417 break;
418 default:
419 throw new InvalidKeyException(
420 "RSA private keys cannot be used with opmode: " + opmode);
421 }
422 } else {
423 // Public key
424 switch (opmode) {
425 case Cipher.ENCRYPT_MODE:
426 case Cipher.WRAP_MODE:
427 // Permitted
428 break;
429 case Cipher.DECRYPT_MODE:
430 case Cipher.UNWRAP_MODE:
431 throw new InvalidKeyException(
432 "RSA public keys cannot be used with " + opmodeToString(opmode)
433 + " and padding "
434 + KeyProperties.EncryptionPadding.fromKeymaster(mKeymasterPadding)
435 + ". Only RSA private keys supported for this opmode.");
436 // break;
437 default:
438 throw new InvalidKeyException(
439 "RSA public keys cannot be used with " + opmodeToString(opmode));
440 }
441 }
442
443 long keySizeBits = -1;
444 for (Authorization a : keystoreKey.getAuthorizations()) {
445 if (a.keyParameter.tag == KeymasterDefs.KM_TAG_KEY_SIZE) {
446 keySizeBits = KeyStore2ParameterUtils.getUnsignedInt(a);
447 }
448 }
449
450 if (keySizeBits == -1) {
451 throw new InvalidKeyException("Size of key not known");
452 } else if (keySizeBits > Integer.MAX_VALUE) {
453 throw new InvalidKeyException("Key too large: " + keySizeBits + " bits");
454 }
455 mModulusSizeBytes = (int) ((keySizeBits + 7) / 8);
456
457 setKey(keystoreKey);
458 }
459
460 /**
461 * Adjusts the configuration of this cipher for encrypting using the private key.
462 *
463 * <p>The default implementation does nothing and refuses to adjust the configuration.
464 *
465 * @return {@code true} if the configuration has been adjusted, {@code false} if encrypting
466 * using private key is not permitted for this cipher.
467 */
468 protected boolean adjustConfigForEncryptingWithPrivateKey() {
469 return false;
470 }
471
472 @Override
473 protected final void resetAll() {
474 mModulusSizeBytes = -1;
475 mKeymasterPaddingOverride = -1;
476 super.resetAll();
477 }
478
479 @Override
480 protected final void resetWhilePreservingInitState() {
481 super.resetWhilePreservingInitState();
482 }
483
484 @Override
485 protected void addAlgorithmSpecificParametersToBegin(
486 @NonNull List<KeyParameter> parameters) {
487 parameters.add(KeyStore2ParameterUtils.makeEnum(
488 KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_RSA
489 ));
490 int keymasterPadding = getKeymasterPaddingOverride();
491 if (keymasterPadding == -1) {
492 keymasterPadding = mKeymasterPadding;
493 }
494 parameters.add(KeyStore2ParameterUtils.makeEnum(
495 KeymasterDefs.KM_TAG_PADDING, keymasterPadding
496 ));
497 int purposeOverride = getKeymasterPurposeOverride();
498 if ((purposeOverride != -1)
499 && ((purposeOverride == KeymasterDefs.KM_PURPOSE_SIGN)
500 || (purposeOverride == KeymasterDefs.KM_PURPOSE_VERIFY))) {
501 // Keymaster sign/verify requires digest to be specified.
502 // For raw sign/verify it's NONE.
503 parameters.add(KeyStore2ParameterUtils.makeEnum(
504 KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_NONE
505 ));
506 }
507 }
508
509 @Override
510 protected void loadAlgorithmSpecificParametersFromBeginResult(
511 KeyParameter[] parameters) {
512 }
513
514 @Override
515 protected final int engineGetBlockSize() {
516 // Not a block cipher, according to the RI
517 return 0;
518 }
519
520 @Override
521 protected final byte[] engineGetIV() {
522 // IV never used
523 return null;
524 }
525
526 @Override
527 protected final int engineGetOutputSize(int inputLen) {
528 return getModulusSizeBytes();
529 }
530
531 protected final int getModulusSizeBytes() {
532 if (mModulusSizeBytes == -1) {
533 throw new IllegalStateException("Not initialized");
534 }
535 return mModulusSizeBytes;
536 }
537
538 /**
539 * Overrides the default padding of the crypto operation.
540 */
541 protected final void setKeymasterPaddingOverride(int keymasterPadding) {
542 mKeymasterPaddingOverride = keymasterPadding;
543 }
544
545 protected final int getKeymasterPaddingOverride() {
546 return mKeymasterPaddingOverride;
547 }
548 }