Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Signature.java
41154 views
1
/*
2
* Copyright (c) 2003, 2021, 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.pkcs11;
27
28
import java.io.IOException;
29
import java.math.BigInteger;
30
import java.nio.ByteBuffer;
31
32
import java.security.*;
33
import java.security.interfaces.*;
34
import java.security.spec.AlgorithmParameterSpec;
35
import sun.nio.ch.DirectBuffer;
36
37
import sun.security.util.*;
38
import sun.security.x509.AlgorithmId;
39
40
import sun.security.rsa.RSASignature;
41
import sun.security.rsa.RSAPadding;
42
43
import sun.security.pkcs11.wrapper.*;
44
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
45
import static sun.security.pkcs11.wrapper.PKCS11Exception.*;
46
import sun.security.util.KeyUtil;
47
48
/**
49
* Signature implementation class. This class currently supports the
50
* following algorithms:
51
*
52
* . DSA
53
* . NONEwithDSA (RawDSA)
54
* . SHA1withDSA
55
* . SHA224withDSA
56
* . SHA256withDSA
57
* . SHA384withDSA
58
* . SHA512withDSA
59
* . SHA3-224withDSA
60
* . SHA3-256withDSA
61
* . SHA3-384withDSA
62
* . SHA3-512withDSA
63
* . <any of above>inP1363Format
64
* . RSA:
65
* . MD2withRSA
66
* . MD5withRSA
67
* . SHA1withRSA
68
* . SHA224withRSA
69
* . SHA256withRSA
70
* . SHA384withRSA
71
* . SHA512withRSA
72
* . SHA3-224withRSA
73
* . SHA3-256withRSA
74
* . SHA3-384withRSA
75
* . SHA3-512withRSA
76
* . ECDSA
77
* . NONEwithECDSA
78
* . SHA1withECDSA
79
* . SHA224withECDSA
80
* . SHA256withECDSA
81
* . SHA384withECDSA
82
* . SHA512withECDSA
83
* . SHA3_224withECDSA
84
* . SHA3_256withECDSA
85
* . SHA3_384withECDSA
86
* . SHA3_512withECDSA
87
* . <any of above>inP1363Format
88
*
89
* Note that the underlying PKCS#11 token may support complete signature
90
* algorithm (e.g. CKM_DSA_SHA1, CKM_MD5_RSA_PKCS), or it may just
91
* implement the signature algorithm without hashing (e.g. CKM_DSA, CKM_PKCS),
92
* or it may only implement the raw public key operation (CKM_RSA_X_509).
93
* This class uses what is available and adds whatever extra processing
94
* is needed.
95
*
96
* @author Andreas Sterbenz
97
* @since 1.5
98
*/
99
final class P11Signature extends SignatureSpi {
100
101
// token instance
102
private final Token token;
103
104
// algorithm name
105
private final String algorithm;
106
107
// name of the key algorithm, currently either RSA or DSA
108
private final String keyAlgorithm;
109
110
// mechanism id
111
private final long mechanism;
112
113
// digest algorithm OID, if we encode RSA signature ourselves
114
private final ObjectIdentifier digestOID;
115
116
// type, one of T_* below
117
private final int type;
118
119
// key instance used, if init*() was called
120
private P11Key p11Key;
121
122
// message digest, if we do the digesting ourselves
123
private final MessageDigest md;
124
125
// associated session, if any
126
private Session session;
127
128
// mode, one of M_* below
129
private int mode;
130
131
// flag indicating whether an operation is initialized
132
private boolean initialized;
133
134
// buffer, for update(byte) or DSA
135
private final byte[] buffer;
136
137
// total number of bytes processed in current operation
138
private int bytesProcessed;
139
140
// The format, to be used for DSA and ECDSA signatures.
141
// If true, the IEEE P1363 format will be used, the concatenation of
142
// r and s. If false (default), the signature will be formatted as a
143
// DER-encoded ASN.1 sequence of r and s.
144
private boolean p1363Format = false;
145
146
// constant for signing mode
147
private static final int M_SIGN = 1;
148
// constant for verification mode
149
private static final int M_VERIFY = 2;
150
151
// constant for type digesting, we do the hashing ourselves
152
private static final int T_DIGEST = 1;
153
// constant for type update, token does everything
154
private static final int T_UPDATE = 2;
155
// constant for type raw, used with RawDSA and NONEwithECDSA only
156
private static final int T_RAW = 3;
157
158
// PKCS#11 spec for CKM_ECDSA states that the length should not be longer
159
// than 1024 bits", but this is a little arbitrary
160
private static final int RAW_ECDSA_MAX = 128;
161
162
163
P11Signature(Token token, String algorithm, long mechanism)
164
throws NoSuchAlgorithmException, PKCS11Exception {
165
super();
166
this.token = token;
167
this.algorithm = algorithm;
168
this.mechanism = mechanism;
169
byte[] buffer = null;
170
ObjectIdentifier digestOID = null;
171
MessageDigest md = null;
172
switch ((int)mechanism) {
173
case (int)CKM_MD2_RSA_PKCS:
174
case (int)CKM_MD5_RSA_PKCS:
175
case (int)CKM_SHA1_RSA_PKCS:
176
case (int)CKM_SHA224_RSA_PKCS:
177
case (int)CKM_SHA256_RSA_PKCS:
178
case (int)CKM_SHA384_RSA_PKCS:
179
case (int)CKM_SHA512_RSA_PKCS:
180
case (int)CKM_SHA3_224_RSA_PKCS:
181
case (int)CKM_SHA3_256_RSA_PKCS:
182
case (int)CKM_SHA3_384_RSA_PKCS:
183
case (int)CKM_SHA3_512_RSA_PKCS:
184
keyAlgorithm = "RSA";
185
type = T_UPDATE;
186
buffer = new byte[1];
187
break;
188
case (int)CKM_DSA_SHA1:
189
case (int)CKM_DSA_SHA224:
190
case (int)CKM_DSA_SHA256:
191
case (int)CKM_DSA_SHA384:
192
case (int)CKM_DSA_SHA512:
193
case (int)CKM_DSA_SHA3_224:
194
case (int)CKM_DSA_SHA3_256:
195
case (int)CKM_DSA_SHA3_384:
196
case (int)CKM_DSA_SHA3_512:
197
keyAlgorithm = "DSA";
198
type = T_UPDATE;
199
buffer = new byte[1];
200
break;
201
case (int)CKM_ECDSA_SHA1:
202
case (int)CKM_ECDSA_SHA224:
203
case (int)CKM_ECDSA_SHA256:
204
case (int)CKM_ECDSA_SHA384:
205
case (int)CKM_ECDSA_SHA512:
206
case (int)CKM_ECDSA_SHA3_224:
207
case (int)CKM_ECDSA_SHA3_256:
208
case (int)CKM_ECDSA_SHA3_384:
209
case (int)CKM_ECDSA_SHA3_512:
210
keyAlgorithm = "EC";
211
type = T_UPDATE;
212
buffer = new byte[1];
213
break;
214
case (int)CKM_DSA:
215
keyAlgorithm = "DSA";
216
if (algorithm.equals("DSA") ||
217
algorithm.equals("DSAinP1363Format")) {
218
type = T_DIGEST;
219
md = MessageDigest.getInstance("SHA-1");
220
} else if (algorithm.equals("RawDSA") ||
221
algorithm.equals("RawDSAinP1363Format")) {
222
type = T_RAW;
223
buffer = new byte[20];
224
} else {
225
throw new ProviderException(algorithm);
226
}
227
break;
228
case (int)CKM_ECDSA:
229
keyAlgorithm = "EC";
230
if (algorithm.equals("NONEwithECDSA") ||
231
algorithm.equals("NONEwithECDSAinP1363Format")) {
232
type = T_RAW;
233
buffer = new byte[RAW_ECDSA_MAX];
234
} else {
235
type = T_DIGEST;
236
md = MessageDigest.getInstance
237
(getDigestEnum(algorithm).stdName());
238
}
239
break;
240
case (int)CKM_RSA_PKCS:
241
case (int)CKM_RSA_X_509:
242
keyAlgorithm = "RSA";
243
type = T_DIGEST;
244
KnownOIDs digestAlg = getDigestEnum(algorithm);
245
md = MessageDigest.getInstance(digestAlg.stdName());
246
digestOID = ObjectIdentifier.of(digestAlg);
247
break;
248
default:
249
throw new ProviderException("Unknown mechanism: " + mechanism);
250
}
251
this.buffer = buffer;
252
this.digestOID = digestOID;
253
this.md = md;
254
if (algorithm.endsWith("inP1363Format")) {
255
this.p1363Format = true;
256
}
257
}
258
259
// reset the states to the pre-initialized values
260
private void reset(boolean doCancel) {
261
262
if (!initialized) {
263
return;
264
}
265
initialized = false;
266
267
try {
268
if (session == null) {
269
return;
270
}
271
272
if (doCancel && token.explicitCancel) {
273
cancelOperation();
274
}
275
} finally {
276
p11Key.releaseKeyID();
277
session = token.releaseSession(session);
278
}
279
}
280
281
private void cancelOperation() {
282
token.ensureValid();
283
// cancel operation by finishing it; avoid killSession as some
284
// hardware vendors may require re-login
285
try {
286
if (mode == M_SIGN) {
287
if (type == T_UPDATE) {
288
token.p11.C_SignFinal(session.id(), 0);
289
} else {
290
byte[] digest;
291
if (type == T_DIGEST) {
292
digest = md.digest();
293
} else { // T_RAW
294
digest = buffer;
295
}
296
token.p11.C_Sign(session.id(), digest);
297
}
298
} else { // M_VERIFY
299
byte[] signature;
300
if (mechanism == CKM_DSA) {
301
signature = new byte[64]; // assume N = 256
302
} else {
303
signature = new byte[(p11Key.length() + 7) >> 3];
304
}
305
if (type == T_UPDATE) {
306
token.p11.C_VerifyFinal(session.id(), signature);
307
} else {
308
byte[] digest;
309
if (type == T_DIGEST) {
310
digest = md.digest();
311
} else { // T_RAW
312
digest = buffer;
313
}
314
token.p11.C_Verify(session.id(), digest, signature);
315
}
316
}
317
} catch (PKCS11Exception e) {
318
if (e.getErrorCode() == CKR_OPERATION_NOT_INITIALIZED) {
319
// Cancel Operation may be invoked after an error on a PKCS#11
320
// call. If the operation inside the token was already cancelled,
321
// do not fail here. This is part of a defensive mechanism for
322
// PKCS#11 libraries that do not strictly follow the standard.
323
return;
324
}
325
if (mode == M_VERIFY) {
326
long errorCode = e.getErrorCode();
327
if ((errorCode == CKR_SIGNATURE_INVALID) ||
328
(errorCode == CKR_SIGNATURE_LEN_RANGE)) {
329
// expected since signature is incorrect
330
return;
331
}
332
}
333
throw new ProviderException("cancel failed", e);
334
}
335
}
336
337
private void ensureInitialized() {
338
339
if (!initialized) {
340
initialize();
341
}
342
}
343
344
// assumes current state is initialized == false
345
private void initialize() {
346
347
if (p11Key == null) {
348
throw new ProviderException(
349
"Operation cannot be performed without " +
350
"calling engineInit first");
351
}
352
long keyID = p11Key.getKeyID();
353
try {
354
token.ensureValid();
355
if (session == null) {
356
session = token.getOpSession();
357
}
358
if (mode == M_SIGN) {
359
token.p11.C_SignInit(session.id(),
360
new CK_MECHANISM(mechanism), keyID);
361
} else {
362
token.p11.C_VerifyInit(session.id(),
363
new CK_MECHANISM(mechanism), keyID);
364
}
365
} catch (PKCS11Exception e) {
366
p11Key.releaseKeyID();
367
session = token.releaseSession(session);
368
throw new ProviderException("Initialization failed", e);
369
}
370
if (bytesProcessed != 0) {
371
bytesProcessed = 0;
372
if (md != null) {
373
md.reset();
374
}
375
}
376
initialized = true;
377
}
378
379
private void checkKeySize(String keyAlgo, Key key)
380
throws InvalidKeyException {
381
CK_MECHANISM_INFO mechInfo = null;
382
try {
383
mechInfo = token.getMechanismInfo(mechanism);
384
} catch (PKCS11Exception e) {
385
// should not happen, ignore for now.
386
}
387
if (mechInfo == null) {
388
// skip the check if no native info available
389
return;
390
}
391
int minKeySize = mechInfo.iMinKeySize;
392
int maxKeySize = mechInfo.iMaxKeySize;
393
394
// need to override the MAX keysize for SHA1withDSA
395
if (md != null && mechanism == CKM_DSA && maxKeySize > 1024) {
396
maxKeySize = 1024;
397
}
398
int keySize = 0;
399
if (key instanceof P11Key) {
400
keySize = ((P11Key) key).length();
401
} else {
402
try {
403
if (keyAlgo.equals("RSA")) {
404
keySize = ((RSAKey) key).getModulus().bitLength();
405
} else if (keyAlgo.equals("DSA")) {
406
keySize = ((DSAKey) key).getParams().getP().bitLength();
407
} else if (keyAlgo.equals("EC")) {
408
keySize = ((ECKey) key).getParams().getCurve().getField().getFieldSize();
409
} else {
410
throw new ProviderException("Error: unsupported algo " + keyAlgo);
411
}
412
} catch (ClassCastException cce) {
413
throw new InvalidKeyException(keyAlgo +
414
" key must be the right type", cce);
415
}
416
}
417
if (keySize < minKeySize) {
418
throw new InvalidKeyException(keyAlgo +
419
" key must be at least " + minKeySize + " bits");
420
}
421
if (keySize > maxKeySize) {
422
throw new InvalidKeyException(keyAlgo +
423
" key must be at most " + maxKeySize + " bits");
424
}
425
if (keyAlgo.equals("RSA")) {
426
checkRSAKeyLength(keySize);
427
}
428
}
429
430
private void checkRSAKeyLength(int len) throws InvalidKeyException {
431
RSAPadding padding;
432
try {
433
padding = RSAPadding.getInstance
434
(RSAPadding.PAD_BLOCKTYPE_1, (len + 7) >> 3);
435
} catch (InvalidAlgorithmParameterException iape) {
436
throw new InvalidKeyException(iape.getMessage());
437
}
438
int maxDataSize = padding.getMaxDataSize();
439
int encodedLength = switch (algorithm) {
440
case "MD5withRSA", "MD2withRSA" -> 34;
441
case "SHA1withRSA" -> 35;
442
case "SHA224withRSA", "SHA3-224withRSA" -> 47;
443
case "SHA256withRSA", "SHA3-256withRSA" -> 51;
444
case "SHA384withRSA", "SHA3-384withRSA" -> 67;
445
case "SHA512withRSA", "SHA3-512withRSA" -> 83;
446
default ->
447
throw new ProviderException("Unknown signature algo: " +
448
algorithm);
449
};
450
if (encodedLength > maxDataSize) {
451
throw new InvalidKeyException
452
("Key is too short for this signature algorithm");
453
}
454
}
455
456
// see JCA spec
457
@Override
458
protected void engineInitVerify(PublicKey publicKey)
459
throws InvalidKeyException {
460
461
if (publicKey == null) {
462
throw new InvalidKeyException("Key must not be null");
463
}
464
// Need to check key length whenever a new key is set
465
if (publicKey != p11Key) {
466
checkKeySize(keyAlgorithm, publicKey);
467
}
468
reset(true);
469
mode = M_VERIFY;
470
p11Key = P11KeyFactory.convertKey(token, publicKey, keyAlgorithm);
471
initialize();
472
}
473
474
// see JCA spec
475
@Override
476
protected void engineInitSign(PrivateKey privateKey)
477
throws InvalidKeyException {
478
479
if (privateKey == null) {
480
throw new InvalidKeyException("Key must not be null");
481
}
482
// Need to check RSA key length whenever a new key is set
483
if (privateKey != p11Key) {
484
checkKeySize(keyAlgorithm, privateKey);
485
}
486
reset(true);
487
mode = M_SIGN;
488
p11Key = P11KeyFactory.convertKey(token, privateKey, keyAlgorithm);
489
initialize();
490
}
491
492
// see JCA spec
493
@Override
494
protected void engineUpdate(byte b) throws SignatureException {
495
ensureInitialized();
496
switch (type) {
497
case T_UPDATE:
498
buffer[0] = b;
499
engineUpdate(buffer, 0, 1);
500
break;
501
case T_DIGEST:
502
md.update(b);
503
bytesProcessed++;
504
break;
505
case T_RAW:
506
if (bytesProcessed >= buffer.length) {
507
bytesProcessed = buffer.length + 1;
508
return;
509
}
510
buffer[bytesProcessed++] = b;
511
break;
512
default:
513
throw new ProviderException("Internal error");
514
}
515
}
516
517
// see JCA spec
518
@Override
519
protected void engineUpdate(byte[] b, int ofs, int len)
520
throws SignatureException {
521
522
ensureInitialized();
523
if (len == 0) {
524
return;
525
}
526
// check for overflow
527
if (len + bytesProcessed < 0) {
528
throw new ProviderException("Processed bytes limits exceeded.");
529
}
530
switch (type) {
531
case T_UPDATE:
532
try {
533
if (mode == M_SIGN) {
534
token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
535
} else {
536
token.p11.C_VerifyUpdate(session.id(), 0, b, ofs, len);
537
}
538
bytesProcessed += len;
539
} catch (PKCS11Exception e) {
540
reset(false);
541
throw new ProviderException(e);
542
}
543
break;
544
case T_DIGEST:
545
md.update(b, ofs, len);
546
bytesProcessed += len;
547
break;
548
case T_RAW:
549
if (bytesProcessed + len > buffer.length) {
550
bytesProcessed = buffer.length + 1;
551
return;
552
}
553
System.arraycopy(b, ofs, buffer, bytesProcessed, len);
554
bytesProcessed += len;
555
break;
556
default:
557
throw new ProviderException("Internal error");
558
}
559
}
560
561
// see JCA spec
562
@Override
563
protected void engineUpdate(ByteBuffer byteBuffer) {
564
565
ensureInitialized();
566
int len = byteBuffer.remaining();
567
if (len <= 0) {
568
return;
569
}
570
switch (type) {
571
case T_UPDATE:
572
if (byteBuffer instanceof DirectBuffer == false) {
573
// cannot do better than default impl
574
super.engineUpdate(byteBuffer);
575
return;
576
}
577
long addr = ((DirectBuffer)byteBuffer).address();
578
int ofs = byteBuffer.position();
579
try {
580
if (mode == M_SIGN) {
581
token.p11.C_SignUpdate
582
(session.id(), addr + ofs, null, 0, len);
583
} else {
584
token.p11.C_VerifyUpdate
585
(session.id(), addr + ofs, null, 0, len);
586
}
587
bytesProcessed += len;
588
byteBuffer.position(ofs + len);
589
} catch (PKCS11Exception e) {
590
reset(false);
591
throw new ProviderException("Update failed", e);
592
}
593
break;
594
case T_DIGEST:
595
md.update(byteBuffer);
596
bytesProcessed += len;
597
break;
598
case T_RAW:
599
if (bytesProcessed + len > buffer.length) {
600
bytesProcessed = buffer.length + 1;
601
return;
602
}
603
byteBuffer.get(buffer, bytesProcessed, len);
604
bytesProcessed += len;
605
break;
606
default:
607
reset(false);
608
throw new ProviderException("Internal error");
609
}
610
}
611
612
// see JCA spec
613
@Override
614
protected byte[] engineSign() throws SignatureException {
615
616
ensureInitialized();
617
boolean doCancel = true;
618
try {
619
byte[] signature;
620
if (type == T_UPDATE) {
621
signature = token.p11.C_SignFinal(session.id(), 0);
622
} else {
623
byte[] digest;
624
if (type == T_DIGEST) {
625
digest = md.digest();
626
} else { // T_RAW
627
if (mechanism == CKM_DSA) {
628
if (bytesProcessed != buffer.length) {
629
throw new SignatureException
630
("Data for RawDSA must be exactly 20 bytes long");
631
}
632
digest = buffer;
633
} else { // CKM_ECDSA
634
if (bytesProcessed > buffer.length) {
635
throw new SignatureException("Data for NONEwithECDSA"
636
+ " must be at most " + RAW_ECDSA_MAX + " bytes long");
637
}
638
digest = new byte[bytesProcessed];
639
System.arraycopy(buffer, 0, digest, 0, bytesProcessed);
640
}
641
}
642
if (keyAlgorithm.equals("RSA") == false) {
643
// DSA and ECDSA
644
signature = token.p11.C_Sign(session.id(), digest);
645
} else { // RSA
646
byte[] data = encodeSignature(digest);
647
if (mechanism == CKM_RSA_X_509) {
648
data = pkcs1Pad(data);
649
}
650
signature = token.p11.C_Sign(session.id(), data);
651
}
652
}
653
doCancel = false;
654
655
if (keyAlgorithm.equals("RSA")) {
656
return signature;
657
} else {
658
if (p1363Format) {
659
return signature;
660
} else {
661
return dsaToASN1(signature);
662
}
663
}
664
} catch (PKCS11Exception pe) {
665
// As per the PKCS#11 standard, C_Sign and C_SignFinal may only
666
// keep the operation active on CKR_BUFFER_TOO_SMALL errors or
667
// successful calls to determine the output length. However,
668
// these cases are handled at OpenJDK's libj2pkcs11 native
669
// library. Thus, doCancel can safely be 'false' here.
670
doCancel = false;
671
throw new ProviderException(pe);
672
} catch (SignatureException | ProviderException e) {
673
throw e;
674
} finally {
675
reset(doCancel);
676
}
677
}
678
679
// see JCA spec
680
@Override
681
protected boolean engineVerify(byte[] signature) throws SignatureException {
682
683
ensureInitialized();
684
boolean doCancel = true;
685
try {
686
if (!p1363Format) {
687
if (keyAlgorithm.equals("DSA")) {
688
signature = asn1ToDSA(signature);
689
} else if (keyAlgorithm.equals("EC")) {
690
signature = asn1ToECDSA(signature);
691
}
692
}
693
if (type == T_UPDATE) {
694
token.p11.C_VerifyFinal(session.id(), signature);
695
} else {
696
byte[] digest;
697
if (type == T_DIGEST) {
698
digest = md.digest();
699
} else { // T_RAW
700
if (mechanism == CKM_DSA) {
701
if (bytesProcessed != buffer.length) {
702
throw new SignatureException
703
("Data for RawDSA must be exactly 20 bytes long");
704
}
705
digest = buffer;
706
} else {
707
if (bytesProcessed > buffer.length) {
708
throw new SignatureException("Data for NONEwithECDSA"
709
+ " must be at most " + RAW_ECDSA_MAX + " bytes long");
710
}
711
digest = new byte[bytesProcessed];
712
System.arraycopy(buffer, 0, digest, 0, bytesProcessed);
713
}
714
}
715
if (keyAlgorithm.equals("RSA") == false) {
716
// DSA and ECDSA
717
token.p11.C_Verify(session.id(), digest, signature);
718
} else { // RSA
719
byte[] data = encodeSignature(digest);
720
if (mechanism == CKM_RSA_X_509) {
721
data = pkcs1Pad(data);
722
}
723
token.p11.C_Verify(session.id(), data, signature);
724
}
725
}
726
doCancel = false;
727
return true;
728
} catch (PKCS11Exception pe) {
729
doCancel = false;
730
long errorCode = pe.getErrorCode();
731
if (errorCode == CKR_SIGNATURE_INVALID) {
732
return false;
733
}
734
if (errorCode == CKR_SIGNATURE_LEN_RANGE) {
735
// return false rather than throwing an exception
736
return false;
737
}
738
// ECF bug?
739
if (errorCode == CKR_DATA_LEN_RANGE) {
740
return false;
741
}
742
throw new ProviderException(pe);
743
} catch (SignatureException | ProviderException e) {
744
throw e;
745
} finally {
746
reset(doCancel);
747
}
748
}
749
750
private byte[] pkcs1Pad(byte[] data) {
751
try {
752
int len = (p11Key.length() + 7) >> 3;
753
RSAPadding padding = RSAPadding.getInstance
754
(RSAPadding.PAD_BLOCKTYPE_1, len);
755
byte[] padded = padding.pad(data);
756
return padded;
757
} catch (GeneralSecurityException e) {
758
throw new ProviderException(e);
759
}
760
}
761
762
private byte[] encodeSignature(byte[] digest) throws SignatureException {
763
try {
764
return RSASignature.encodeSignature(digestOID, digest);
765
} catch (IOException e) {
766
throw new SignatureException("Invalid encoding", e);
767
}
768
}
769
770
private static KnownOIDs getDigestEnum(String algorithm)
771
throws NoSuchAlgorithmException {
772
try {
773
String digAlg = SignatureUtil.extractDigestAlgFromDwithE(algorithm);
774
KnownOIDs k = KnownOIDs.findMatch(digAlg);
775
if (k == null) {
776
throw new NoSuchAlgorithmException
777
("Unsupported digest algorithm: " + digAlg);
778
}
779
return k;
780
} catch (IllegalArgumentException iae) {
781
// should never happen
782
throw new NoSuchAlgorithmException("Unknown signature: " +
783
algorithm, iae);
784
}
785
}
786
787
// private static byte[] decodeSignature(byte[] signature) throws IOException {
788
// return RSASignature.decodeSignature(digestOID, signature);
789
// }
790
791
// For DSA and ECDSA signatures, PKCS#11 represents them as a simple
792
// byte array that contains the concatenation of r and s.
793
// For DSA, r and s are always exactly 20 bytes long.
794
// For ECDSA, r and s are of variable length, but we know that each
795
// occupies half of the array.
796
private static byte[] dsaToASN1(byte[] signature) {
797
int n = signature.length >> 1;
798
BigInteger r = new BigInteger(1, P11Util.subarray(signature, 0, n));
799
BigInteger s = new BigInteger(1, P11Util.subarray(signature, n, n));
800
try {
801
DerOutputStream outseq = new DerOutputStream(100);
802
outseq.putInteger(r);
803
outseq.putInteger(s);
804
DerValue result = new DerValue(DerValue.tag_Sequence,
805
outseq.toByteArray());
806
return result.toByteArray();
807
} catch (java.io.IOException e) {
808
throw new RuntimeException("Internal error", e);
809
}
810
}
811
812
private static byte[] asn1ToDSA(byte[] sig) throws SignatureException {
813
try {
814
// Enforce strict DER checking for signatures
815
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
816
DerValue[] values = in.getSequence(2);
817
818
// check number of components in the read sequence
819
// and trailing data
820
if ((values.length != 2) || (in.available() != 0)) {
821
throw new IOException("Invalid encoding for signature");
822
}
823
824
BigInteger r = values[0].getPositiveBigInteger();
825
BigInteger s = values[1].getPositiveBigInteger();
826
827
byte[] br = toByteArray(r, 20);
828
byte[] bs = toByteArray(s, 20);
829
if ((br == null) || (bs == null)) {
830
throw new SignatureException("Out of range value for R or S");
831
}
832
return P11Util.concat(br, bs);
833
} catch (SignatureException e) {
834
throw e;
835
} catch (Exception e) {
836
throw new SignatureException("Invalid encoding for signature", e);
837
}
838
}
839
840
private byte[] asn1ToECDSA(byte[] sig) throws SignatureException {
841
try {
842
// Enforce strict DER checking for signatures
843
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
844
DerValue[] values = in.getSequence(2);
845
846
// check number of components in the read sequence
847
// and trailing data
848
if ((values.length != 2) || (in.available() != 0)) {
849
throw new IOException("Invalid encoding for signature");
850
}
851
852
BigInteger r = values[0].getPositiveBigInteger();
853
BigInteger s = values[1].getPositiveBigInteger();
854
855
// trim leading zeroes
856
byte[] br = KeyUtil.trimZeroes(r.toByteArray());
857
byte[] bs = KeyUtil.trimZeroes(s.toByteArray());
858
int k = Math.max(br.length, bs.length);
859
// r and s each occupy half the array
860
byte[] res = new byte[k << 1];
861
System.arraycopy(br, 0, res, k - br.length, br.length);
862
System.arraycopy(bs, 0, res, res.length - bs.length, bs.length);
863
return res;
864
} catch (Exception e) {
865
throw new SignatureException("Invalid encoding for signature", e);
866
}
867
}
868
869
private static byte[] toByteArray(BigInteger bi, int len) {
870
byte[] b = bi.toByteArray();
871
int n = b.length;
872
if (n == len) {
873
return b;
874
}
875
if ((n == len + 1) && (b[0] == 0)) {
876
byte[] t = new byte[len];
877
System.arraycopy(b, 1, t, 0, len);
878
return t;
879
}
880
if (n > len) {
881
return null;
882
}
883
// must be smaller
884
byte[] t = new byte[len];
885
System.arraycopy(b, 0, t, (len - n), n);
886
return t;
887
}
888
889
// see JCA spec
890
@SuppressWarnings("deprecation")
891
@Override
892
protected void engineSetParameter(String param, Object value)
893
throws InvalidParameterException {
894
throw new UnsupportedOperationException("setParameter() not supported");
895
}
896
897
// see JCA spec
898
@Override
899
protected void engineSetParameter(AlgorithmParameterSpec params)
900
throws InvalidAlgorithmParameterException {
901
if (params != null) {
902
throw new InvalidAlgorithmParameterException("No parameter accepted");
903
}
904
}
905
906
// see JCA spec
907
@SuppressWarnings("deprecation")
908
@Override
909
protected Object engineGetParameter(String param)
910
throws InvalidParameterException {
911
throw new UnsupportedOperationException("getParameter() not supported");
912
}
913
914
// see JCA spec
915
@Override
916
protected AlgorithmParameters engineGetParameters() {
917
return null;
918
}
919
}
920
921