-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Expand file tree
/
Copy pathSignature.java
More file actions
1439 lines (1339 loc) · 56.2 KB
/
Signature.java
File metadata and controls
1439 lines (1339 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.io.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.nio.ByteBuffer;
import java.security.Provider.Service;
import jdk.internal.access.JavaSecuritySignatureAccess;
import jdk.internal.access.SharedSecrets;
import sun.security.util.Debug;
import sun.security.util.CryptoAlgorithmConstraints;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
import sun.security.util.KnownOIDs;
/**
* The {@code Signature} class is used to provide applications the functionality
* of a digital signature algorithm. Digital signatures are used for
* authentication and integrity assurance of digital data.
*
* <p> The signature algorithm can be, among others, the NIST standard
* DSA, using DSA and SHA-256. The DSA algorithm using the
* SHA-256 message digest algorithm can be specified as {@code SHA256withDSA}.
* In the case of RSA the signing algorithm could be specified as, for example,
* {@code SHA256withRSA}.
* The algorithm name must be specified, as there is no default.
*
* <p> A {@code Signature} object can be used to generate and verify digital
* signatures.
*
* <p> There are three phases to the use of a {@code Signature} object for
* either signing data or verifying a signature:<ol>
*
* <li>Initialization, with either
*
* <ul>
*
* <li>a public key, which initializes the signature for
* verification (see {@link #initVerify(PublicKey) initVerify}), or
*
* <li>a private key (and optionally a Secure Random Number Generator),
* which initializes the signature for signing
* (see {@link #initSign(PrivateKey)}
* and {@link #initSign(PrivateKey, SecureRandom)}).
*
* </ul>
*
* <li>Updating
*
* <p>Depending on the type of initialization, this will update the
* bytes to be signed or verified. See the
* {@link #update(byte) update} methods.
*
* <li>Signing or Verifying a signature on all updated bytes. See the
* {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
* method.
*
* </ol>
*
* <p>Note that this class is abstract and extends from
* {@code SignatureSpi} for historical reasons.
* Application developers should only take notice of the methods defined in
* this {@code Signature} class; all the methods in
* the superclass are intended for cryptographic service providers who wish to
* supply their own implementations of digital signature algorithms.
*
* <p> Every implementation of the Java platform is required to support the
* following standard {@code Signature} algorithms. For the "RSASSA-PSS"
* algorithm, implementations must support the parameters in parentheses. For
* the "SHA256withECDSA" and "SHA384withECDSA" algorithms, implementations must
* support the curves in parentheses.
* <ul>
* <li>{@code RSASSA-PSS} (MGF1 mask generation function and SHA-256 or SHA-384
* hash algorithms)</li>
* <li>{@code SHA1withDSA}</li>
* <li>{@code SHA256withDSA}</li>
* <li>{@code SHA256withECDSA} (secp256r1)</li>
* <li>{@code SHA384withECDSA} (secp384r1)</li>
* <li>{@code SHA1withRSA}</li>
* <li>{@code SHA256withRSA}</li>
* <li>{@code SHA384withRSA}</li>
* </ul>
* These algorithms are described in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
* Signature section</a> of the
* Java Security Standard Algorithm Names Specification.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @author Benjamin Renaud
* @since 1.1
*
*/
public abstract class Signature extends SignatureSpi {
static {
SharedSecrets.setJavaSecuritySignatureAccess(
new JavaSecuritySignatureAccess() {
@Override
public void initVerify(Signature s, PublicKey publicKey,
AlgorithmParameterSpec params)
throws InvalidKeyException,
InvalidAlgorithmParameterException {
s.initVerify(publicKey, params);
}
@Override
public void initVerify(Signature s,
java.security.cert.Certificate certificate,
AlgorithmParameterSpec params)
throws InvalidKeyException,
InvalidAlgorithmParameterException {
s.initVerify(certificate, params);
}
@Override
public void initSign(Signature s, PrivateKey privateKey,
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException,
InvalidAlgorithmParameterException {
s.initSign(privateKey, params, random);
}
});
}
private static final Debug debug =
Debug.getInstance("jca", "Signature");
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("signature");
/*
* The algorithm for this signature object.
* This value is used to map an OID to the particular algorithm.
* The mapping is done in AlgorithmObject.algOID(String algorithm)
*/
private String algorithm;
// The provider
Provider provider;
/**
* Possible {@link #state} value, signifying that
* this {@code Signature} object has not yet been initialized.
*/
protected static final int UNINITIALIZED = 0;
/**
* Possible {@link #state} value, signifying that
* this {@code Signature} object has been initialized for signing.
*/
protected static final int SIGN = 2;
/**
* Possible {@link #state} value, signifying that
* this {@code Signature} object has been initialized for verification.
*/
protected static final int VERIFY = 3;
/**
* Current state of this {@code Signature} object.
*/
protected int state = UNINITIALIZED;
/**
* Creates a {@code Signature} object for the specified algorithm.
*
* @param algorithm the standard string name of the algorithm.
* See the Signature section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard algorithm names.
* @spec security/standard-names.html Java Security Standard Algorithm Names
*/
protected Signature(String algorithm) {
this.algorithm = algorithm;
}
/**
* Returns a {@code Signature} object that implements the specified
* signature algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new {@code Signature} object encapsulating the
* {@code SignatureSpi} implementation from the first
* provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @implNote
* The JDK Reference Implementation additionally uses the following
* security properties:
* <ul>
* <li>the {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different from the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
* </li>
* <li>the {@code jdk.crypto.disabledAlgorithms}
* {@link Security#getProperty(String) Security} property to determine
* if the specified algorithm is allowed. If the
* {@systemProperty jdk.crypto.disabledAlgorithms} is set, it supersedes
* the security property value.
* </li>
* </ul>
*
* @param algorithm the standard name of the algorithm requested.
* See the Signature section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard algorithm names.
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return the new {@code Signature} object
*
* @throws NoSuchAlgorithmException if no {@code Provider} supports a
* {@code Signature} implementation for the
* specified algorithm
*
* @throws NullPointerException if {@code algorithm} is {@code null}
*
* @see Provider
*/
public static Signature getInstance(String algorithm)
throws NoSuchAlgorithmException {
Objects.requireNonNull(algorithm, "null algorithm name");
if (!CryptoAlgorithmConstraints.permits("Signature", algorithm)) {
throw new NoSuchAlgorithmException(algorithm + " is disabled");
}
Iterator<Service> t = GetInstance.getServices("Signature", algorithm);
if (!t.hasNext()) {
throw new NoSuchAlgorithmException
(algorithm + " Signature not available");
}
// try services until we find an Spi or a working Signature subclass
NoSuchAlgorithmException failure;
do {
Service s = t.next();
if (isSpi(s)) { // delayed provider selection
return new Delegate(s, t, algorithm);
} else {
// must be a subclass of Signature, disable dynamic selection
try {
Instance instance =
GetInstance.getInstance(s, SignatureSpi.class);
return getInstance(instance, algorithm);
} catch (NoSuchAlgorithmException e) {
failure = e;
}
}
} while (t.hasNext());
throw failure;
}
private static Signature getInstance(Instance instance, String algorithm) {
Signature sig;
if (instance.impl instanceof Signature) {
sig = (Signature)instance.impl;
sig.algorithm = algorithm;
} else {
SignatureSpi spi = (SignatureSpi)instance.impl;
sig = Delegate.of(spi, algorithm);
}
sig.provider = instance.provider;
return sig;
}
private static final Map<String,Boolean> signatureInfo;
static {
signatureInfo = new ConcurrentHashMap<>();
// pre-initialize with values for our SignatureSpi implementations
signatureInfo.put("sun.security.provider.DSA$RawDSA", true);
signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", true);
signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", true);
signatureInfo.put("sun.security.rsa.RSAPSSSignature", true);
signatureInfo.put("sun.security.pkcs11.P11Signature", true);
}
private static boolean isSpi(Service s) {
String className = s.getClassName();
Boolean result = signatureInfo.get(className);
if (result == null) {
try {
Object instance = s.newInstance(null);
// Signature extends SignatureSpi
// so it is a "real" Spi if it is an
// instance of SignatureSpi but not Signature
boolean r = (instance instanceof SignatureSpi)
&& (!(instance instanceof Signature));
if ((debug != null) && (!r)) {
debug.println("Not a SignatureSpi " + className);
debug.println("Delayed provider selection may not be "
+ "available for algorithm " + s.getAlgorithm());
}
result = Boolean.valueOf(r);
signatureInfo.put(className, result);
} catch (Exception e) {
// something is wrong, assume not an SPI
return false;
}
}
return result.booleanValue();
}
/**
* Returns a {@code Signature} object that implements the specified
* signature algorithm.
*
* <p> A new {@code Signature} object encapsulating the
* {@code SignatureSpi} implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @implNote
* The JDK Reference Implementation additionally uses
* the {@code jdk.crypto.disabledAlgorithms}
* {@link Security#getProperty(String) Security} property to determine
* if the specified algorithm is allowed. If the
* {@systemProperty jdk.crypto.disabledAlgorithms} is set, it supersedes
* the security property value.
*
* @param algorithm the name of the algorithm requested.
* See the Signature section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return the new {@code Signature} object
*
* @throws IllegalArgumentException if the provider name is {@code null}
* or empty
*
* @throws NoSuchAlgorithmException if a {@code SignatureSpi}
* implementation for the specified algorithm is not
* available from the specified provider
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list
*
* @throws NullPointerException if {@code algorithm} is {@code null}
*
* @see Provider
*/
public static Signature getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Objects.requireNonNull(algorithm, "null algorithm name");
if (!CryptoAlgorithmConstraints.permits("Signature", algorithm)) {
throw new NoSuchAlgorithmException(algorithm + " is disabled");
}
Instance instance = GetInstance.getInstance
("Signature", SignatureSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
}
/**
* Returns a {@code Signature} object that implements the specified
* signature algorithm.
*
* <p> A new {@code Signature} object encapsulating the
* {@code SignatureSpi} implementation from the specified provider
* is returned. Note that the specified provider does not
* have to be registered in the provider list.
*
* @implNote
* The JDK Reference Implementation additionally uses
* the {@code jdk.crypto.disabledAlgorithms}
* {@link Security#getProperty(String) Security} property to determine
* if the specified algorithm is allowed. If the
* {@systemProperty jdk.crypto.disabledAlgorithms} is set, it supersedes
* the security property value.
*
* @param algorithm the name of the algorithm requested.
* See the Signature section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return the new {@code Signature} object
*
* @throws IllegalArgumentException if the provider is {@code null}
*
* @throws NoSuchAlgorithmException if a {@code SignatureSpi}
* implementation for the specified algorithm is not available
* from the specified {@code Provider} object
*
* @throws NullPointerException if {@code algorithm} is {@code null}
*
* @see Provider
*
* @since 1.4
*/
public static Signature getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException {
Objects.requireNonNull(algorithm, "null algorithm name");
if (!CryptoAlgorithmConstraints.permits("Signature", algorithm)) {
throw new NoSuchAlgorithmException(algorithm + " is disabled");
}
Instance instance = GetInstance.getInstance
("Signature", SignatureSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
}
/**
* Returns the provider of this {@code Signature} object.
*
* @return the provider of this {@code Signature} object
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
private String getProviderName() {
return (provider == null) ? "(no provider)" : provider.getName();
}
void chooseFirstProvider() {
// empty, overridden in Delegate
}
/**
* Initializes this object for verification. If this method is called
* again with a different argument, it negates the effect
* of this call.
*
* @param publicKey the public key of the identity whose signature is
* going to be verified.
*
* @throws InvalidKeyException if the key is invalid.
*/
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException {
engineInitVerify(publicKey);
state = VERIFY;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" verification algorithm from: " + getProviderName());
}
}
/**
* Initialize this object for verification. If this method is called
* again with different arguments, it negates the effect
* of this call.
*
* @param publicKey the public key of the identity whose signature is
* going to be verified
* @param params the parameters used for verifying this {@code Signature}
* object
*
* @throws InvalidKeyException if the key is invalid
* @throws InvalidAlgorithmParameterException if the params is invalid
*/
final void initVerify(PublicKey publicKey, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
engineInitVerify(publicKey, params);
state = VERIFY;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" verification algorithm from: " + getProviderName());
}
}
private static PublicKey getPublicKeyFromCert(Certificate cert)
throws InvalidKeyException {
// If the certificate is of type X509Certificate,
// we should check whether it has a Key Usage
// extension marked as critical.
//if (cert instanceof java.security.cert.X509Certificate) {
if (cert instanceof X509Certificate xcert) {
// Check whether the cert has a key usage extension
// marked as a critical extension.
// The OID for KeyUsage extension is 2.5.29.15.
Set<String> critSet = xcert.getCriticalExtensionOIDs();
if (critSet != null && !critSet.isEmpty()
&& critSet.contains(KnownOIDs.KeyUsage.value())) {
boolean[] keyUsageInfo = xcert.getKeyUsage();
// keyUsageInfo[0] is for digitalSignature.
if ((keyUsageInfo != null) && (!keyUsageInfo[0]))
throw new InvalidKeyException("Wrong key usage");
}
}
return cert.getPublicKey();
}
/**
* Initializes this object for verification, using the public key from
* the given certificate.
* <p>If the certificate is of type X.509 and has a <i>key usage</i>
* extension field marked as critical, and the value of the <i>key usage</i>
* extension field implies that the public key in
* the certificate and its corresponding private key are not
* supposed to be used for digital signatures, an
* {@code InvalidKeyException} is thrown.
*
* @param certificate the certificate of the identity whose signature is
* going to be verified.
*
* @throws InvalidKeyException if the public key in the certificate
* is not encoded properly or does not include required parameter
* information or cannot be used for digital signature purposes.
* @since 1.3
*/
public final void initVerify(Certificate certificate)
throws InvalidKeyException {
engineInitVerify(getPublicKeyFromCert(certificate));
state = VERIFY;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" verification algorithm from: " + getProviderName());
}
}
/**
* Initializes this object for verification, using the public key from
* the given certificate.
* <p>If the certificate is of type X.509 and has a <i>key usage</i>
* extension field marked as critical, and the value of the <i>key usage</i>
* extension field implies that the public key in
* the certificate and its corresponding private key are not
* supposed to be used for digital signatures, an
* {@code InvalidKeyException} is thrown.
*
* @param certificate the certificate of the identity whose signature is
* going to be verified
* @param params the parameters used for verifying this {@code Signature}
* object
*
* @throws InvalidKeyException if the public key in the certificate
* is not encoded properly or does not include required parameter
* information or cannot be used for digital signature purposes
* @throws InvalidAlgorithmParameterException if the params is invalid
*
* @since 13
*/
final void initVerify(Certificate certificate,
AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
engineInitVerify(getPublicKeyFromCert(certificate), params);
state = VERIFY;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" verification algorithm from: " + getProviderName());
}
}
/**
* Initialize this object for signing. If this method is called
* again with a different argument, it negates the effect
* of this call.
*
* @param privateKey the private key of the identity whose signature
* is going to be generated.
*
* @throws InvalidKeyException if the key is invalid.
*/
public final void initSign(PrivateKey privateKey)
throws InvalidKeyException {
engineInitSign(privateKey);
state = SIGN;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" signing algorithm from: " + getProviderName());
}
}
/**
* Initialize this object for signing. If this method is called
* again with a different argument, it negates the effect
* of this call.
*
* @param privateKey the private key of the identity whose signature
* is going to be generated
*
* @param random the source of randomness for this {@code Signature} object
*
* @throws InvalidKeyException if the key is invalid.
*/
public final void initSign(PrivateKey privateKey, SecureRandom random)
throws InvalidKeyException {
engineInitSign(privateKey, random);
state = SIGN;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" signing algorithm from: " + getProviderName());
}
}
/**
* Initialize this object for signing. If this method is called
* again with different arguments, it negates the effect
* of this call.
*
* @param privateKey the private key of the identity whose signature
* is going to be generated
* @param params the parameters used for generating signature
* @param random the source of randomness for this {@code Signature} object
*
* @throws InvalidKeyException if the key is invalid
* @throws InvalidAlgorithmParameterException if the params is invalid
*/
final void initSign(PrivateKey privateKey,
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
engineInitSign(privateKey, params, random);
state = SIGN;
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" signing algorithm from: " + getProviderName());
}
}
/**
* Returns the signature bytes of all the data updated.
* The format of the signature depends on the underlying
* signature scheme.
*
* <p>A call to this method resets this {@code Signature} object to the
* state it was in when previously initialized for signing via a
* call to {@code initSign(PrivateKey)}. That is, the object is
* reset and available to generate another signature from the same
* signer, if desired, via new calls to {@code update} and
* {@code sign}.
*
* @return the signature bytes of the signing operation's result.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly or if this signature algorithm is unable to
* process the input data provided.
*/
public final byte[] sign() throws SignatureException {
if (state == SIGN) {
return engineSign();
}
throw new SignatureException("object not initialized for " +
"signing");
}
/**
* Finishes the signature operation and stores the resulting signature
* bytes in the provided buffer {@code outbuf}, starting at
* {@code offset}.
* The format of the signature depends on the underlying
* signature scheme.
*
* <p>This {@code Signature} object is reset to its initial state (the
* state it was in after a call to one of the {@code initSign} methods) and
* can be reused to generate further signatures with the same private key.
*
* @param outbuf buffer for the signature result.
*
* @param offset offset into {@code outbuf} where the signature is
* stored.
*
* @param len number of bytes within {@code outbuf} allotted for the
* signature.
*
* @return the number of bytes placed into {@code outbuf}.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly, if this signature algorithm is unable to
* process the input data provided, or if {@code len} is less
* than the actual signature length.
* @throws IllegalArgumentException if {@code outbuf} is {@code null},
* or {@code offset} or {@code len} is less than 0, or the sum of
* {@code offset} and {@code len} is greater than the length of
* {@code outbuf}.
*
* @since 1.2
*/
public final int sign(byte[] outbuf, int offset, int len)
throws SignatureException {
if (outbuf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (offset < 0 || len < 0) {
throw new IllegalArgumentException("offset or len is less than 0");
}
if (outbuf.length - offset < len) {
throw new IllegalArgumentException
("Output buffer too small for specified offset and length");
}
if (state != SIGN) {
throw new SignatureException("object not initialized for " +
"signing");
}
return engineSign(outbuf, offset, len);
}
/**
* Verifies the passed-in signature.
*
* <p>A call to this method resets this {@code Signature} object to the
* state it was in when previously initialized for verification via a
* call to {@code initVerify(PublicKey)}. That is, the object is
* reset and available to verify another signature from the identity
* whose public key was specified in the call to {@code initVerify}.
*
* @param signature the signature bytes to be verified.
*
* @return {@code true} if the signature was verified, {@code false} if not.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly, the passed-in signature is improperly
* encoded or of the wrong type, if this signature algorithm is unable to
* process the input data provided, etc.
*/
public final boolean verify(byte[] signature) throws SignatureException {
if (state == VERIFY) {
return engineVerify(signature);
}
throw new SignatureException("object not initialized for " +
"verification");
}
/**
* Verifies the passed-in signature in the specified array
* of bytes, starting at the specified offset.
*
* <p>A call to this method resets this {@code Signature} object to the
* state it was in when previously initialized for verification via a
* call to {@code initVerify(PublicKey)}. That is, the object is
* reset and available to verify another signature from the identity
* whose public key was specified in the call to {@code initVerify}.
*
*
* @param signature the signature bytes to be verified.
* @param offset the offset to start from in the array of bytes.
* @param length the number of bytes to use, starting at offset.
*
* @return {@code true} if the signature was verified, {@code false} if not.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly, the passed-in signature is improperly
* encoded or of the wrong type, if this signature algorithm is unable to
* process the input data provided, etc.
* @throws IllegalArgumentException if the {@code signature}
* byte array is {@code null}, or the {@code offset} or {@code length}
* is less than 0, or the sum of the {@code offset} and
* {@code length} is greater than the length of the
* {@code signature} byte array.
* @since 1.4
*/
public final boolean verify(byte[] signature, int offset, int length)
throws SignatureException {
if (state == VERIFY) {
if (signature == null) {
throw new IllegalArgumentException("signature is null");
}
if (offset < 0 || length < 0) {
throw new IllegalArgumentException
("offset or length is less than 0");
}
if (signature.length - offset < length) {
throw new IllegalArgumentException
("signature too small for specified offset and length");
}
return engineVerify(signature, offset, length);
}
throw new SignatureException("object not initialized for " +
"verification");
}
/**
* Updates the data to be signed or verified by a byte.
*
* @param b the byte to use for the update.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly.
*/
public final void update(byte b) throws SignatureException {
if (state == VERIFY || state == SIGN) {
engineUpdate(b);
} else {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
}
/**
* Updates the data to be signed or verified, using the specified
* array of bytes.
*
* @param data the byte array to use for the update.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly.
*/
public final void update(byte[] data) throws SignatureException {
update(data, 0, data.length);
}
/**
* Updates the data to be signed or verified, using the specified
* array of bytes, starting at the specified offset.
*
* @param data the array of bytes.
* @param off the offset to start from in the array of bytes.
* @param len the number of bytes to use, starting at offset.
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly.
* @throws IllegalArgumentException if {@code data} is {@code null},
* or {@code off} or {@code len} is less than 0, or the sum of
* {@code off} and {@code len} is greater than the length of
* {@code data}.
*/
public final void update(byte[] data, int off, int len)
throws SignatureException {
if (state == SIGN || state == VERIFY) {
if (data == null) {
throw new IllegalArgumentException("data is null");
}
if (off < 0 || len < 0) {
throw new IllegalArgumentException("off or len is less than 0");
}
if (data.length - off < len) {
throw new IllegalArgumentException
("data too small for specified offset and length");
}
engineUpdate(data, off, len);
} else {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
}
/**
* Updates the data to be signed or verified using the specified
* ByteBuffer. Processes the {@code data.remaining()} bytes
* starting at {@code data.position()}.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* @param data the ByteBuffer
*
* @throws SignatureException if this {@code Signature} object is not
* initialized properly.
* @since 1.5
*/
public final void update(ByteBuffer data) throws SignatureException {
if ((state != SIGN) && (state != VERIFY)) {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
if (data == null) {
throw new NullPointerException();
}
engineUpdate(data);
}
/**
* Returns the name of the algorithm for this {@code Signature} object.
*
* @return the name of the algorithm for this {@code Signature} object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* Returns a string representation of this {@code Signature} object,
* providing information that includes the state of the object
* and the name of the algorithm used.
*
* @return a string representation of this {@code Signature} object.
*/
public String toString() {
String initState = switch (state) {
case UNINITIALIZED -> "<not initialized>";
case VERIFY -> "<initialized for verifying>";
case SIGN -> "<initialized for signing>";
default -> "";
};
return "Signature object: " + getAlgorithm() + initState;
}
/**
* Sets the specified algorithm parameter to the specified value.
* This method supplies a general-purpose mechanism through
* which it is possible to set the various parameters of this object.
* A parameter may be any settable parameter for the algorithm, such as
* a parameter size, or a source of random bits for signature generation
* (if appropriate), or an indication of whether to perform
* a specific but optional computation. A uniform algorithm-specific
* naming scheme for each parameter is desirable but left unspecified
* at this time.
*
* @param param the string identifier of the parameter
* @param value the parameter value
*
* @throws InvalidParameterException if {@code param} is an
* invalid parameter for this {@code Signature} object,
* the parameter is already set
* and cannot be set again, a security exception occurs, and so on.
*
* @see #getParameter
*
* @deprecated Use
* {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
* setParameter}.
*/
@Deprecated
public final void setParameter(String param, Object value)
throws InvalidParameterException {
engineSetParameter(param, value);
}
/**
* Initializes this {@code Signature} object with the specified parameter
* values.
*
* @param params the parameter values
*
* @throws InvalidAlgorithmParameterException if the given parameter values
* are inappropriate for this {@code Signature} object
*
* @see #getParameters
*/
public final void setParameter(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
engineSetParameter(params);
}
/**
* Returns the parameters used with this {@code Signature} object.
*
* <p>The returned parameters may be the same that were used to initialize
* this {@code Signature} object, or may contain additional default or
* random parameter values used by the underlying signature scheme.
* If the required parameters were not supplied and can be generated by