Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java
41159 views
1
/*
2
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.rsa;
27
28
import java.io.IOException;
29
import java.nio.ByteBuffer;
30
31
import java.security.*;
32
import java.security.spec.AlgorithmParameterSpec;
33
import java.security.spec.PSSParameterSpec;
34
import java.security.spec.MGF1ParameterSpec;
35
import java.security.interfaces.*;
36
37
import java.util.Arrays;
38
import java.util.Hashtable;
39
40
import sun.security.util.*;
41
import sun.security.jca.JCAUtil;
42
43
44
/**
45
* PKCS#1 v2.2 RSASSA-PSS signatures with various message digest algorithms.
46
* RSASSA-PSS implementation takes the message digest algorithm, MGF algorithm,
47
* and salt length values through the required signature PSS parameters.
48
* We support SHA-1, SHA-2 family and SHA3 family of message digest algorithms,
49
* and MGF1 mask generation function.
50
*
51
* @since 11
52
*/
53
public class RSAPSSSignature extends SignatureSpi {
54
55
private static final boolean DEBUG = false;
56
57
// utility method for comparing digest algorithms
58
// NOTE that first argument is assumed to be standard digest name
59
private boolean isDigestEqual(String stdAlg, String givenAlg) {
60
if (stdAlg == null || givenAlg == null) return false;
61
62
if (givenAlg.indexOf("-") != -1) {
63
return stdAlg.equalsIgnoreCase(givenAlg);
64
} else {
65
if (stdAlg.equals("SHA-1")) {
66
return (givenAlg.equalsIgnoreCase("SHA")
67
|| givenAlg.equalsIgnoreCase("SHA1"));
68
} else {
69
StringBuilder sb = new StringBuilder(givenAlg);
70
// case-insensitive check
71
if (givenAlg.regionMatches(true, 0, "SHA", 0, 3)) {
72
givenAlg = sb.insert(3, "-").toString();
73
return stdAlg.equalsIgnoreCase(givenAlg);
74
} else {
75
throw new ProviderException("Unsupported digest algorithm "
76
+ givenAlg);
77
}
78
}
79
}
80
}
81
82
private static final byte[] EIGHT_BYTES_OF_ZEROS = new byte[8];
83
84
private static final Hashtable<KnownOIDs, Integer> DIGEST_LENGTHS =
85
new Hashtable<KnownOIDs, Integer>();
86
static {
87
DIGEST_LENGTHS.put(KnownOIDs.SHA_1, 20);
88
DIGEST_LENGTHS.put(KnownOIDs.SHA_224, 28);
89
DIGEST_LENGTHS.put(KnownOIDs.SHA_256, 32);
90
DIGEST_LENGTHS.put(KnownOIDs.SHA_384, 48);
91
DIGEST_LENGTHS.put(KnownOIDs.SHA_512, 64);
92
DIGEST_LENGTHS.put(KnownOIDs.SHA_512$224, 28);
93
DIGEST_LENGTHS.put(KnownOIDs.SHA_512$256, 32);
94
DIGEST_LENGTHS.put(KnownOIDs.SHA3_224, 28);
95
DIGEST_LENGTHS.put(KnownOIDs.SHA3_256, 32);
96
DIGEST_LENGTHS.put(KnownOIDs.SHA3_384, 48);
97
DIGEST_LENGTHS.put(KnownOIDs.SHA3_512, 64);
98
}
99
100
// message digest implementation we use for hashing the data
101
private MessageDigest md;
102
// flag indicating whether the digest is reset
103
private boolean digestReset = true;
104
105
// private key, if initialized for signing
106
private RSAPrivateKey privKey = null;
107
// public key, if initialized for verifying
108
private RSAPublicKey pubKey = null;
109
// PSS parameters from signatures and keys respectively
110
private PSSParameterSpec sigParams = null; // required for PSS signatures
111
112
// PRNG used to generate salt bytes if none given
113
private SecureRandom random;
114
115
/**
116
* Construct a new RSAPSSSignatur with arbitrary digest algorithm
117
*/
118
public RSAPSSSignature() {
119
this.md = null;
120
}
121
122
// initialize for verification. See JCA doc
123
@Override
124
protected void engineInitVerify(PublicKey publicKey)
125
throws InvalidKeyException {
126
if (!(publicKey instanceof RSAPublicKey)) {
127
throw new InvalidKeyException("key must be RSAPublicKey");
128
}
129
this.pubKey = (RSAPublicKey) isValid((RSAKey)publicKey);
130
this.privKey = null;
131
resetDigest();
132
}
133
134
// initialize for signing. See JCA doc
135
@Override
136
protected void engineInitSign(PrivateKey privateKey)
137
throws InvalidKeyException {
138
engineInitSign(privateKey, null);
139
}
140
141
// initialize for signing. See JCA doc
142
@Override
143
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
144
throws InvalidKeyException {
145
if (!(privateKey instanceof RSAPrivateKey)) {
146
throw new InvalidKeyException("key must be RSAPrivateKey");
147
}
148
this.privKey = (RSAPrivateKey) isValid((RSAKey)privateKey);
149
this.pubKey = null;
150
this.random =
151
(random == null? JCAUtil.getSecureRandom() : random);
152
resetDigest();
153
}
154
155
/**
156
* Utility method for checking the key PSS parameters against signature
157
* PSS parameters.
158
* Returns false if any of the digest/MGF algorithms and trailerField
159
* values does not match or if the salt length in key parameters is
160
* larger than the value in signature parameters.
161
*/
162
private static boolean isCompatible(AlgorithmParameterSpec keyParams,
163
PSSParameterSpec sigParams) {
164
if (keyParams == null) {
165
// key with null PSS parameters means no restriction
166
return true;
167
}
168
if (!(keyParams instanceof PSSParameterSpec)) {
169
return false;
170
}
171
// nothing to compare yet, defer the check to when sigParams is set
172
if (sigParams == null) {
173
return true;
174
}
175
PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;
176
// first check the salt length requirement
177
if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {
178
return false;
179
}
180
181
// compare equality of the rest of fields based on DER encoding
182
PSSParameterSpec keyParams2 =
183
new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),
184
pssKeyParams.getMGFAlgorithm(),
185
pssKeyParams.getMGFParameters(),
186
sigParams.getSaltLength(),
187
pssKeyParams.getTrailerField());
188
PSSParameters ap = new PSSParameters();
189
// skip the JCA overhead
190
try {
191
ap.engineInit(keyParams2);
192
byte[] encoded = ap.engineGetEncoded();
193
ap.engineInit(sigParams);
194
byte[] encoded2 = ap.engineGetEncoded();
195
return Arrays.equals(encoded, encoded2);
196
} catch (Exception e) {
197
if (DEBUG) {
198
e.printStackTrace();
199
}
200
return false;
201
}
202
}
203
204
/**
205
* Validate the specified RSAKey and its associated parameters against
206
* internal signature parameters.
207
*/
208
private RSAKey isValid(RSAKey rsaKey) throws InvalidKeyException {
209
AlgorithmParameterSpec keyParams = rsaKey.getParams();
210
// validate key parameters
211
if (!isCompatible(rsaKey.getParams(), this.sigParams)) {
212
throw new InvalidKeyException
213
("Key contains incompatible PSS parameter values");
214
}
215
// validate key length
216
if (this.sigParams != null) {
217
String digestAlgo = this.sigParams.getDigestAlgorithm();
218
KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);
219
if (ko != null) {
220
Integer hLen = DIGEST_LENGTHS.get(ko);
221
if (hLen != null) {
222
checkKeyLength(rsaKey, hLen,
223
this.sigParams.getSaltLength());
224
} else {
225
// should never happen; checked in validateSigParams()
226
throw new ProviderException
227
("Unsupported digest algo: " + digestAlgo);
228
}
229
} else {
230
// should never happen; checked in validateSigParams()
231
throw new ProviderException
232
("Unrecognized digest algo: " + digestAlgo);
233
}
234
}
235
return rsaKey;
236
}
237
238
/**
239
* Validate the specified Signature PSS parameters.
240
*/
241
private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)
242
throws InvalidAlgorithmParameterException {
243
if (p == null) {
244
throw new InvalidAlgorithmParameterException
245
("Parameters cannot be null");
246
}
247
if (!(p instanceof PSSParameterSpec)) {
248
throw new InvalidAlgorithmParameterException
249
("parameters must be type PSSParameterSpec");
250
}
251
// no need to validate again if same as current signature parameters
252
PSSParameterSpec params = (PSSParameterSpec) p;
253
if (params == this.sigParams) return params;
254
255
RSAKey key = (this.privKey == null? this.pubKey : this.privKey);
256
// check against keyParams if set
257
if (key != null) {
258
if (!isCompatible(key.getParams(), params)) {
259
throw new InvalidAlgorithmParameterException
260
("Signature parameters does not match key parameters");
261
}
262
}
263
// now sanity check the parameter values
264
if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {
265
throw new InvalidAlgorithmParameterException("Only supports MGF1");
266
267
}
268
if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
269
throw new InvalidAlgorithmParameterException
270
("Only supports TrailerFieldBC(1)");
271
272
}
273
274
// check key length again
275
if (key != null) {
276
String digestAlgo = params.getDigestAlgorithm();
277
KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);
278
if (ko != null) {
279
Integer hLen = DIGEST_LENGTHS.get(ko);
280
if (hLen != null) {
281
try {
282
checkKeyLength(key, hLen, params.getSaltLength());
283
} catch (InvalidKeyException e) {
284
throw new InvalidAlgorithmParameterException(e);
285
}
286
} else {
287
throw new InvalidAlgorithmParameterException
288
("Unsupported digest algo: " + digestAlgo);
289
}
290
} else {
291
throw new InvalidAlgorithmParameterException
292
("Unrecognized digest algo: " + digestAlgo);
293
}
294
}
295
return params;
296
}
297
298
/**
299
* Ensure the object is initialized with key and parameters and
300
* reset digest
301
*/
302
private void ensureInit() throws SignatureException {
303
RSAKey key = (this.privKey == null? this.pubKey : this.privKey);
304
if (key == null) {
305
throw new SignatureException("Missing key");
306
}
307
if (this.sigParams == null) {
308
// Parameters are required for signature verification
309
throw new SignatureException
310
("Parameters required for RSASSA-PSS signatures");
311
}
312
}
313
314
/**
315
* Utility method for checking key length against digest length and
316
* salt length
317
*/
318
private static void checkKeyLength(RSAKey key, int digestLen,
319
int saltLen) throws InvalidKeyException {
320
if (key != null) {
321
int keyLength = (getKeyLengthInBits(key) + 7) >> 3;
322
int minLength = Math.addExact(Math.addExact(digestLen, saltLen), 2);
323
if (keyLength < minLength) {
324
throw new InvalidKeyException
325
("Key is too short, need min " + minLength + " bytes");
326
}
327
}
328
}
329
330
/**
331
* Reset the message digest if it is not already reset.
332
*/
333
private void resetDigest() {
334
if (digestReset == false) {
335
this.md.reset();
336
digestReset = true;
337
}
338
}
339
340
/**
341
* Return the message digest value.
342
*/
343
private byte[] getDigestValue() {
344
digestReset = true;
345
return this.md.digest();
346
}
347
348
// update the signature with the plaintext data. See JCA doc
349
@Override
350
protected void engineUpdate(byte b) throws SignatureException {
351
ensureInit();
352
this.md.update(b);
353
digestReset = false;
354
}
355
356
// update the signature with the plaintext data. See JCA doc
357
@Override
358
protected void engineUpdate(byte[] b, int off, int len)
359
throws SignatureException {
360
ensureInit();
361
this.md.update(b, off, len);
362
digestReset = false;
363
}
364
365
// update the signature with the plaintext data. See JCA doc
366
@Override
367
protected void engineUpdate(ByteBuffer b) {
368
try {
369
ensureInit();
370
} catch (SignatureException se) {
371
// hack for working around API bug
372
throw new RuntimeException(se.getMessage());
373
}
374
this.md.update(b);
375
digestReset = false;
376
}
377
378
// sign the data and return the signature. See JCA doc
379
@Override
380
protected byte[] engineSign() throws SignatureException {
381
ensureInit();
382
byte[] mHash = getDigestValue();
383
try {
384
byte[] encoded = encodeSignature(mHash);
385
byte[] encrypted = RSACore.rsa(encoded, privKey, true);
386
return encrypted;
387
} catch (GeneralSecurityException e) {
388
throw new SignatureException("Could not sign data", e);
389
} catch (IOException e) {
390
throw new SignatureException("Could not encode data", e);
391
}
392
}
393
394
// verify the data and return the result. See JCA doc
395
// should be reset to the state after engineInitVerify call.
396
@Override
397
protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
398
ensureInit();
399
try {
400
if (sigBytes.length != RSACore.getByteLength(this.pubKey)) {
401
throw new SignatureException
402
("Signature length not correct: got "
403
+ sigBytes.length + " but was expecting "
404
+ RSACore.getByteLength(this.pubKey));
405
}
406
byte[] mHash = getDigestValue();
407
byte[] decrypted = RSACore.rsa(sigBytes, this.pubKey);
408
return decodeSignature(mHash, decrypted);
409
} catch (javax.crypto.BadPaddingException e) {
410
// occurs if the app has used the wrong RSA public key
411
// or if sigBytes is invalid
412
// return false rather than propagating the exception for
413
// compatibility/ease of use
414
return false;
415
} catch (IOException e) {
416
throw new SignatureException("Signature encoding error", e);
417
} finally {
418
resetDigest();
419
}
420
}
421
422
// return the modulus length in bits
423
private static int getKeyLengthInBits(RSAKey k) {
424
if (k != null) {
425
return k.getModulus().bitLength();
426
}
427
return -1;
428
}
429
430
/**
431
* Encode the digest 'mHash', return the to-be-signed data.
432
* Also used by the PKCS#11 provider.
433
*/
434
private byte[] encodeSignature(byte[] mHash)
435
throws IOException, DigestException {
436
AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();
437
String mgfDigestAlgo;
438
if (mgfParams != null) {
439
mgfDigestAlgo =
440
((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();
441
} else {
442
mgfDigestAlgo = this.md.getAlgorithm();
443
}
444
try {
445
int emBits = getKeyLengthInBits(this.privKey) - 1;
446
int emLen = (emBits + 7) >> 3;
447
int hLen = this.md.getDigestLength();
448
int dbLen = emLen - hLen - 1;
449
int sLen = this.sigParams.getSaltLength();
450
451
// maps DB into the corresponding region of EM and
452
// stores its bytes directly into EM
453
byte[] em = new byte[emLen];
454
455
// step7 and some of step8
456
em[dbLen - sLen - 1] = (byte) 1; // set DB's padding2 into EM
457
em[em.length - 1] = (byte) 0xBC; // set trailer field of EM
458
459
if (!digestReset) {
460
throw new ProviderException("Digest should be reset");
461
}
462
// step5: generates M' using padding1, mHash, and salt
463
this.md.update(EIGHT_BYTES_OF_ZEROS);
464
digestReset = false; // mark digest as it now has data
465
this.md.update(mHash);
466
if (sLen != 0) {
467
// step4: generate random salt
468
byte[] salt = new byte[sLen];
469
this.random.nextBytes(salt);
470
this.md.update(salt);
471
472
// step8: set DB's salt into EM
473
System.arraycopy(salt, 0, em, dbLen - sLen, sLen);
474
}
475
// step6: generate H using M'
476
this.md.digest(em, dbLen, hLen); // set H field of EM
477
digestReset = true;
478
479
// step7 and 8 are already covered by the code which setting up
480
// EM as above
481
482
// step9 and 10: feed H into MGF and xor with DB in EM
483
MGF1 mgf1 = new MGF1(mgfDigestAlgo);
484
mgf1.generateAndXor(em, dbLen, hLen, dbLen, em, 0);
485
486
// step11: set the leftmost (8emLen - emBits) bits of the leftmost
487
// octet to 0
488
int numZeroBits = (emLen << 3) - emBits;
489
490
if (numZeroBits != 0) {
491
byte MASK = (byte) (0xff >>> numZeroBits);
492
em[0] = (byte) (em[0] & MASK);
493
}
494
495
// step12: em should now holds maskedDB || hash h || 0xBC
496
return em;
497
} catch (NoSuchAlgorithmException e) {
498
throw new IOException(e.toString());
499
}
500
}
501
502
/**
503
* Decode the signature data as under RFC8017 sec9.1.2 EMSA-PSS-VERIFY
504
*/
505
private boolean decodeSignature(byte[] mHash, byte[] em)
506
throws IOException {
507
int hLen = mHash.length;
508
int sLen = this.sigParams.getSaltLength();
509
int emBits = getKeyLengthInBits(this.pubKey) - 1;
510
int emLen = (emBits + 7) >> 3;
511
512
// When key length is 8N+1 bits (N+1 bytes), emBits = 8N,
513
// emLen = N which is one byte shorter than em.length.
514
// Otherwise, emLen should be same as em.length
515
int emOfs = em.length - emLen;
516
if ((emOfs == 1) && (em[0] != 0)) {
517
return false;
518
}
519
520
// step3
521
if (emLen < (hLen + sLen + 2)) {
522
return false;
523
}
524
525
// step4
526
if (em[emOfs + emLen - 1] != (byte) 0xBC) {
527
return false;
528
}
529
530
// step6: check if the leftmost (8emLen - emBits) bits of the leftmost
531
// octet are 0
532
int numZeroBits = (emLen << 3) - emBits;
533
534
if (numZeroBits != 0) {
535
byte MASK = (byte) (0xff << (8 - numZeroBits));
536
if ((em[emOfs] & MASK) != 0) {
537
return false;
538
}
539
}
540
String mgfDigestAlgo;
541
AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();
542
if (mgfParams != null) {
543
mgfDigestAlgo =
544
((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();
545
} else {
546
mgfDigestAlgo = this.md.getAlgorithm();
547
}
548
// step 7 and 8
549
int dbLen = emLen - hLen - 1;
550
try {
551
MGF1 mgf1 = new MGF1(mgfDigestAlgo);
552
mgf1.generateAndXor(em, emOfs + dbLen, hLen, dbLen,
553
em, emOfs);
554
} catch (NoSuchAlgorithmException nsae) {
555
throw new IOException(nsae.toString());
556
}
557
558
// step9: set the leftmost (8emLen - emBits) bits of the leftmost
559
// octet to 0
560
if (numZeroBits != 0) {
561
byte MASK = (byte) (0xff >>> numZeroBits);
562
em[emOfs] = (byte) (em[emOfs] & MASK);
563
}
564
565
// step10
566
int i = emOfs;
567
for (; i < emOfs + (dbLen - sLen - 1); i++) {
568
if (em[i] != 0) {
569
return false;
570
}
571
}
572
if (em[i] != 0x01) {
573
return false;
574
}
575
// step12 and 13
576
this.md.update(EIGHT_BYTES_OF_ZEROS);
577
digestReset = false;
578
this.md.update(mHash);
579
if (sLen > 0) {
580
this.md.update(em, emOfs + (dbLen - sLen), sLen);
581
}
582
byte[] digest2 = this.md.digest();
583
digestReset = true;
584
585
// step14
586
byte[] digestInEM = Arrays.copyOfRange(em, emOfs + dbLen,
587
emOfs + emLen - 1);
588
return MessageDigest.isEqual(digest2, digestInEM);
589
}
590
591
// set parameter, not supported. See JCA doc
592
@Deprecated
593
@Override
594
protected void engineSetParameter(String param, Object value)
595
throws InvalidParameterException {
596
throw new UnsupportedOperationException("setParameter() not supported");
597
}
598
599
@Override
600
protected void engineSetParameter(AlgorithmParameterSpec params)
601
throws InvalidAlgorithmParameterException {
602
this.sigParams = validateSigParams(params);
603
// disallow changing parameters when digest has been used
604
if (!digestReset) {
605
throw new ProviderException
606
("Cannot set parameters during operations");
607
}
608
String newHashAlg = this.sigParams.getDigestAlgorithm();
609
// re-allocate md if not yet assigned or algorithm changed
610
if ((this.md == null) ||
611
!(this.md.getAlgorithm().equalsIgnoreCase(newHashAlg))) {
612
try {
613
this.md = MessageDigest.getInstance(newHashAlg);
614
} catch (NoSuchAlgorithmException nsae) {
615
// should not happen as we pick default digest algorithm
616
throw new InvalidAlgorithmParameterException
617
("Unsupported digest algorithm " +
618
newHashAlg, nsae);
619
}
620
}
621
}
622
623
// get parameter, not supported. See JCA doc
624
@Deprecated
625
@Override
626
protected Object engineGetParameter(String param)
627
throws InvalidParameterException {
628
throw new UnsupportedOperationException("getParameter() not supported");
629
}
630
631
@Override
632
protected AlgorithmParameters engineGetParameters() {
633
AlgorithmParameters ap = null;
634
if (this.sigParams != null) {
635
try {
636
ap = AlgorithmParameters.getInstance("RSASSA-PSS");
637
ap.init(this.sigParams);
638
} catch (GeneralSecurityException gse) {
639
throw new ProviderException(gse.getMessage());
640
}
641
}
642
return ap;
643
}
644
}
645
646