API Overview API Index Package Overview Direct link to this page
JDK 1.6
  java.security. Signature View Javadoc
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261

/*
 * @(#)Signature.java	1.103 06/04/21
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
  
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 javax.crypto.Cipher;
import javax.crypto.CipherSpi;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import javax.crypto.NoSuchPaddingException;

import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;

/**
 * This 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-1. The DSA algorithm using the
 * SHA-1 message digest algorithm can be specified as <tt>SHA1withDSA</tt>.
 * In the case of RSA, there are multiple choices for the message digest
 * algorithm, so the signing algorithm could be specified as, for example,
 * <tt>MD2withRSA</tt>, <tt>MD5withRSA</tt>, or <tt>SHA1withRSA</tt>.
 * The algorithm name must be specified, as there is no default.
 *
 * <p> A Signature object can be used to generate and verify digital
 * signatures.
 *
 * <p> There are three phases to the use of a 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><p>
 *
 * <li>Updating<p>
 *
 * <p>Depending on the type of initialization, this will update the
 * bytes to be signed or verified. See the 
 * {@link #update(byte) update} methods.<p>
 *
 * <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</code> for historical reasons.
 * Application developers should only take notice of the methods defined in
 * this <code>Signature</code> class; all the methods in
 * the superclass are intended for cryptographic service providers who wish to
 * supply their own implementations of digital signature algorithms.
 *
 * @author Benjamin Renaud 
 *
 * @version 1.103, 04/21/06
 */

public abstract class Signature extends SignatureSpi {

    private static final Debug debug =
			Debug.getInstance("jca", "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 signature object has not yet been initialized.
     */      
    protected final static int UNINITIALIZED = 0;       
       
    /** 
     * Possible {@link #state} value, signifying that       
     * this signature object has been initialized for signing.
     */      
    protected final static int SIGN = 2;
       
    /** 
     * Possible {@link #state} value, signifying that       
     * this signature object has been initialized for verification.
     */      
    protected final static int VERIFY = 3;

    /** 
     * Current state of this signature object.
     */      
    protected int state = UNINITIALIZED;

    /**
     * Creates a Signature object for the specified algorithm.
     *
     * @param algorithm the standard string name of the algorithm. 
     * See Appendix A in the <a href=
     * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture API Specification &amp; Reference </a> 
     * for information about standard algorithm names.
     */
    protected Signature(String algorithm) {
	this.algorithm = algorithm;
    }
    
    // name of the special signature alg
    private final static String RSA_SIGNATURE = "NONEwithRSA";

    // name of the equivalent cipher alg
    private final static String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
    
    // all the services we need to lookup for compatibility with Cipher
    private final static List<ServiceId> rsaIds = Arrays.asList(
	new ServiceId[] {
	    new ServiceId("Signature", "NONEwithRSA"),
	    new ServiceId("Cipher", "RSA/ECB/PKCS1Padding"),
	    new ServiceId("Cipher", "RSA/ECB"),
	    new ServiceId("Cipher", "RSA//PKCS1Padding"),
	    new ServiceId("Cipher", "RSA"),
	}
    );

    /**
     * Returns a 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 Signature object encapsulating the
     * 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.
     *
     * @param algorithm the standard name of the algorithm requested. 
     * See Appendix A in the <a href=
     * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture API Specification &amp; Reference </a> 
     * for information about standard algorithm names.
     *
     * @return the new Signature object.
     *
     * @exception NoSuchAlgorithmException if no Provider supports a
     *          Signature implementation for the
     *          specified algorithm.
     *
     * @see Provider
     */
    public static Signature getInstance(String algorithm) 
	    throws NoSuchAlgorithmException {
	List list;
	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    list = GetInstance.getServices(rsaIds);
	} else {
	    list = GetInstance.getServices("Signature", algorithm);
	}
	Iterator t = list.iterator();
	if (t.hasNext() == false) {
	    throw new NoSuchAlgorithmException
	    	(algorithm + " Signature not available");
	}
	// try services until we find an Spi or a working Signature subclass
	NoSuchAlgorithmException failure;
	do {
	    Service s = (Service)t.next();
	    if (isSpi(s)) {
		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;
	} else {
	    SignatureSpi spi = (SignatureSpi)instance.impl;
	    sig = new Delegate(spi, algorithm);
	}
	sig.provider = instance.provider;
	return sig;
    }
    
    private final static Map<String,Boolean> signatureInfo;
    
    static {
    	signatureInfo = new ConcurrentHashMap<String,Boolean>();
	Boolean TRUE = Boolean.TRUE;
	// 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("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
	signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
    }
    
    private static boolean isSpi(Service s) {
	if (s.getType().equals("Cipher")) {
	    // must be a CipherSpi, which we can wrap with the CipherAdapter
	    return true;
	}
	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 == false);
		if ((debug != null) && (r == false)) {
		    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 Signature object that implements the specified signature
     * algorithm.
     *
     * <p> A new Signature object encapsulating the
     * 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.
     *
     * @param algorithm the name of the algorithm requested.
     * See Appendix A in the <a href=
     * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture API Specification &amp; Reference </a> 
     * for information about standard algorithm names.
     *
     * @param provider the name of the provider.
     *
     * @return the new Signature object.
     *
     * @exception NoSuchAlgorithmException if a SignatureSpi
     *		implementation for the specified algorithm is not
     *		available from the specified provider.
     *
     * @exception NoSuchProviderException if the specified provider is not
     *		registered in the security provider list.
     *
     * @exception IllegalArgumentException if the provider name is null
     *		or empty.
     * 
     * @see Provider 
     */
    public static Signature getInstance(String algorithm, String provider) 
	    throws NoSuchAlgorithmException, NoSuchProviderException {
	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    // exception compatibility with existing code
	    if ((provider == null) || (provider.length() == 0)) {
		throw new IllegalArgumentException("missing provider");
	    }
	    Provider p = Security.getProvider(provider);
	    if (p == null) {
		throw new NoSuchProviderException
		    ("no such provider: " + provider);
	    }
	    return getInstanceRSA(p);
	}
	Instance instance = GetInstance.getInstance
		("Signature", SignatureSpi.class, algorithm, provider);
	return getInstance(instance, algorithm);
    }
    
    /** 
     * Returns a Signature object that implements the specified
     * signature algorithm.
     *
     * <p> A new Signature object encapsulating the
     * SignatureSpi implementation from the specified Provider
     * object is returned.  Note that the specified Provider object
     * does not have to be registered in the provider list.
     *
     * @param algorithm the name of the algorithm requested.
     * See Appendix A in the <a href=
     * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture API Specification &amp; Reference </a> 
     * for information about standard algorithm names.
     *
     * @param provider the provider.
     *
     * @return the new Signature object.
     *
     * @exception NoSuchAlgorithmException if a SignatureSpi
     *		implementation for the specified algorithm is not available
     *		from the specified Provider object.
     *
     * @exception IllegalArgumentException if the provider is null.
     * 
     * @see Provider
     *
     * @since 1.4
     */
    public static Signature getInstance(String algorithm, Provider provider) 
	    throws NoSuchAlgorithmException {
	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    // exception compatibility with existing code
	    if (provider == null) {
		throw new IllegalArgumentException("missing provider");
	    }
	    return getInstanceRSA(provider);
	}
	Instance instance = GetInstance.getInstance
		("Signature", SignatureSpi.class, algorithm, provider);
	return getInstance(instance, algorithm);
    }

    // return an implementation for NONEwithRSA, which is a special case
    // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
    private static Signature getInstanceRSA(Provider p)
	    throws NoSuchAlgorithmException {
	// try Signature first
	Service s = p.getService("Signature", RSA_SIGNATURE);
	if (s != null) {
	    Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
	    return getInstance(instance, RSA_SIGNATURE);
	}
	// check Cipher
	try {
	    Cipher c = Cipher.getInstance(RSA_CIPHER, p);
	    return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
	} catch (GeneralSecurityException e) {
	    // throw Signature style exception message to avoid confusion,
	    // but append Cipher exception as cause
	    throw new NoSuchAlgorithmException("no such algorithm: "
		+ RSA_SIGNATURE + " for provider " + p.getName(), e);
	}
    }

    /** 
     * Returns the provider of this signature object.
     * 
     * @return the provider of this signature object
     */
    public final Provider getProvider() {
	chooseFirstProvider();
	return this.provider;
    }
    
    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.
     *
     * @exception InvalidKeyException if the key is invalid.
     */
    public final void initVerify(PublicKey publicKey) 
	    throws InvalidKeyException {
	engineInitVerify(publicKey);
	state = VERIFY;
    }

    /**
     * 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</code> is thrown.
     *
     * @param certificate the certificate of the identity whose signature is
     * going to be verified.
     *
     * @exception 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 {
	// If the certificate is of type X509Certificate,
	// we should check whether it has a Key Usage
	// extension marked as critical.
	if (certificate instanceof java.security.cert.X509Certificate) {
	    // Check whether the cert has a key usage extension
	    // marked as a critical extension.
	    // The OID for KeyUsage extension is 2.5.29.15.
	    X509Certificate cert = (X509Certificate)certificate;
	    Set critSet = cert.getCriticalExtensionOIDs();

	    if (critSet != null && !critSet.isEmpty()
		&& critSet.contains("2.5.29.15")) {
		boolean[] keyUsageInfo = cert.getKeyUsage();
		// keyUsageInfo[0] is for digitalSignature.
		if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
		    throw new InvalidKeyException("Wrong key usage");
	    }
	}
	    
	PublicKey publicKey = certificate.getPublicKey();
	engineInitVerify(publicKey);
	state = VERIFY;
    }

    /**
     * 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.
     * 
     * @exception InvalidKeyException if the key is invalid.  
     */
    public final void initSign(PrivateKey privateKey) 
	    throws InvalidKeyException {
	engineInitSign(privateKey);
	state = SIGN;
    }

    /**
     * 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 signature.
     * 
     * @exception InvalidKeyException if the key is invalid.  
     */
    public final void initSign(PrivateKey privateKey, SecureRandom random) 
	    throws InvalidKeyException {
	engineInitSign(privateKey, random);
	state = SIGN;
    }

    /**
     * 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 signature object to the state 
     * it was in when previously initialized for signing via a
     * call to <code>initSign(PrivateKey)</code>. That is, the object is 
     * reset and available to generate another signature from the same 
     * signer, if desired, via new calls to <code>update</code> and 
     * <code>sign</code>.     
     *
     * @return the signature bytes of the signing operation's result.
     *
     * @exception SignatureException if this 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</code>, starting at
     * <code>offset</code>. 
     * The format of the signature depends on the underlying 
     * signature scheme.
     * 
     * <p>This signature object is reset to its initial state (the state it
     * was in after a call to one of the <code>initSign</code> 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</code> where the signature is
     * stored.
     *
     * @param len number of bytes within <code>outbuf</code> allotted for the
     * signature.
     *
     * @return the number of bytes placed into <code>outbuf</code>.
     *
     * @exception SignatureException if this signature object is not
     * initialized properly, if this signature algorithm is unable to
     * process the input data provided, or if <code>len</code> is less
     * than the actual signature length.
     *
     * @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 (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 signature object to the state 
     * it was in when previously initialized for verification via a
     * call to <code>initVerify(PublicKey)</code>. 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</code>.
     *      
     * @param signature the signature bytes to be verified.
     *
     * @return true if the signature was verified, false if not. 
     *
     * @exception SignatureException if this 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 signature object to the state 
     * it was in when previously initialized for verification via a
     * call to <code>initVerify(PublicKey)</code>. 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</code>.
     *
     *      
     * @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 true if the signature was verified, false if not. 
     *
     * @exception SignatureException if this 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.
     * @exception IllegalArgumentException if the <code>signature</code>
     * byte array is null, or the <code>offset</code> or <code>length</code>
     * is less than 0, or the sum of the <code>offset</code> and 
     * <code>length</code> is greater than the length of the
     * <code>signature</code> byte array.
     * @since 1.4
     */
    public final boolean verify(byte[] signature, int offset, int length)
	throws SignatureException {
	if (state == VERIFY) {
	    if ((signature == null) || (offset < 0) || (length < 0) ||
		(offset + length > signature.length)) {
		throw new IllegalArgumentException("Bad arguments");
	    }

	    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.
     * 
     * @exception SignatureException if this 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.       
     * 
     * @exception SignatureException if this 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.
     *  
     * @exception SignatureException if this signature object is not 
     * initialized properly.          
     */
    public final void update(byte[] data, int off, int len) 
	    throws SignatureException {
	if (state == SIGN || state == VERIFY) {
	    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()</code> bytes
     * starting at at <code>data.position()</code>.
     * Upon return, the buffer's position will be equal to its limit;
     * its limit will not have changed.
     *
     * @param data the ByteBuffer
     *
     * @exception SignatureException if this 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 signature object.
     * 
     * @return the name of the algorithm for this signature object.
     */
    public final String getAlgorithm() {
	return this.algorithm;
    }

    /**
     * Returns a string representation of this signature object,       
     * providing information that includes the state of the object       
     * and the name of the algorithm used.       
     * 
     * @return a string representation of this signature object.
     */
    public String toString() {
	String initState = "";
	switch (state) {
	case UNINITIALIZED:
	    initState = "<not initialized>";
	    break;
	case VERIFY:
	    initState = "<initialized for verifying>";
	    break;	      
	case SIGN:
	    initState = "<initialized for signing>";
	    break;	      
	}
	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 or not 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.
     *
     * @exception InvalidParameterException if <code>param</code> is an
     * invalid parameter for this signature algorithm engine,
     * 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 signature engine with the specified parameter set.
     *
     * @param params the parameters
     *
     * @exception InvalidAlgorithmParameterException if the given parameters
     * are inappropriate for this signature engine
     *
     * @see #getParameters
     */
    public final void setParameter(AlgorithmParameterSpec params)
	    throws InvalidAlgorithmParameterException {
	engineSetParameter(params);
    }

    /**
     * Returns the parameters used with this signature object.
     *
     * <p>The returned parameters may be the same that were used to initialize
     * this signature, or may contain a combination of default and randomly
     * generated parameter values used by the underlying signature 
     * implementation if this signature requires algorithm parameters but 
     * was not initialized with any.
     *
     * @return the parameters used with this signature, or null if this
     * signature does not use any parameters.
     *
     * @see #setParameter(AlgorithmParameterSpec)
     * @since 1.4
     */
    public final AlgorithmParameters getParameters() {
	return engineGetParameters();
    }    

    /**
     * Gets the value of the specified algorithm parameter. This method 
     * supplies a general-purpose mechanism through which it is possible to 
     * get 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 or not 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 name of the parameter.
     *
     * @return the object that represents the parameter value, or null if
     * there is none.
     *
     * @exception InvalidParameterException if <code>param</code> is an invalid
     * parameter for this engine, or another exception occurs while
     * trying to get this parameter.
     *
     * @see #setParameter(String, Object)
     *
     * @deprecated
     */
@Deprecated
    public final Object getParameter(String param) 
	    throws InvalidParameterException {
	return engineGetParameter(param);
    }

    /**
     * Returns a clone if the implementation is cloneable.
     * 
     * @return a clone if the implementation is cloneable.
     *
     * @exception CloneNotSupportedException if this is called
     * on an implementation that does not support <code>Cloneable</code>.
     */
    public Object clone() throws CloneNotSupportedException {
	if (this instanceof Cloneable) {
	    return super.clone();
	} else {
	    throw new CloneNotSupportedException();
	}
    }
    
    /*
     * The following class allows providers to extend from SignatureSpi
     * rather than from Signature. It represents a Signature with an
     * encapsulated, provider-supplied SPI object (of type SignatureSpi).
     * If the provider implementation is an instance of SignatureSpi, the
     * getInstance() methods above return an instance of this class, with
     * the SPI object encapsulated.
     *
     * Note: All SPI methods from the original Signature class have been
     * moved up the hierarchy into a new class (SignatureSpi), which has
     * been interposed in the hierarchy between the API (Signature)
     * and its original parent (Object).
     */

    private static class Delegate extends Signature {

	// The provider implementation (delegate)
	// filled in once the provider is selected
	private SignatureSpi sigSpi;
	
	// lock for mutex during provider selection
	private final Object lock;

	// next service to try in provider selection
	// null once provider is selected
	private Service firstService;
	
	// remaining services to try in provider selection
	// null once provider is selected
	private Iterator serviceIterator;
	
	// constructor
	Delegate(SignatureSpi sigSpi, String algorithm) {
	    super(algorithm);
	    this.sigSpi = sigSpi;
	    this.lock = null; // no lock needed
	}
	
	// used with delayed provider selection
	Delegate(Service service, Iterator iterator, String algorithm) {
	    super(algorithm);
	    this.firstService = service;
	    this.serviceIterator = iterator;
	    this.lock = new Object();
	}
	
	/**
	 * Returns a clone if the delegate is cloneable.    
	 * 
	 * @return a clone if the delegate is cloneable.
	 *
	 * @exception CloneNotSupportedException if this is called on a
	 * delegate that does not support <code>Cloneable</code>.
	 */
	public Object clone() throws CloneNotSupportedException {
	    chooseFirstProvider();
	    if (sigSpi instanceof Cloneable) {
		SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
		// Because 'algorithm' and 'provider' are private
		// members of our supertype, we must perform a cast to
		// access them.
		Signature that =
		    new Delegate(sigSpiClone, ((Signature)this).algorithm);
		that.provider = ((Signature)this).provider;
		return that;
	    } else {
		throw new CloneNotSupportedException();
	    }
	}
	
	private static SignatureSpi newInstance(Service s) 
		throws NoSuchAlgorithmException {
	    if (s.getType().equals("Cipher")) {
		// must be NONEwithRSA
		try {
		    Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
		    return new CipherAdapter(c);
		} catch (NoSuchPaddingException e) {
		    throw new NoSuchAlgorithmException(e);
		}
	    } else {
		Object o = s.newInstance(null);
		if (o instanceof SignatureSpi == false) {
		    throw new NoSuchAlgorithmException
			("Not a SignatureSpi: " + o.getClass().getName());
		}
		return (SignatureSpi)o;
	    }
	}

	// max number of debug warnings to print from chooseFirstProvider()
	private static int warnCount = 10;

	/**
	 * Choose the Spi from the first provider available. Used if
	 * delayed provider selection is not possible because initSign()/
	 * initVerify() is not the first method called.
	 */
	void chooseFirstProvider() {
	    if (sigSpi != null) {
		return;
	    }
	    synchronized (lock) {
		if (sigSpi != null) {
		    return;
		}
		if (debug != null) {
		    int w = --warnCount;
		    if (w >= 0) {
			debug.println("Signature.init() not first method "
			    + "called, disabling delayed provider selection");
			if (w == 0) {
			    debug.println("Further warnings of this type will "
			    	+ "be suppressed");
			}
			new Exception("Call trace").printStackTrace();
		    }
		}
		Exception lastException = null;
		while ((firstService != null) || serviceIterator.hasNext()) {
		    Service s;
		    if (firstService != null) {
			s = firstService;
			firstService = null;
		    } else {
			s = (Service)serviceIterator.next();
		    }
		    if (isSpi(s) == false) {
			continue;
		    }
		    try {
			sigSpi = newInstance(s);
			provider = s.getProvider();
			// not needed any more
			firstService = null;
			serviceIterator = null;
			return;
		    } catch (NoSuchAlgorithmException e) {
			lastException = e;
		    }
		}
		ProviderException e = new ProviderException
			("Could not construct SignatureSpi instance");
		if (lastException != null) {
		    e.initCause(lastException);
		}
		throw e;
	    }
	}
	
	private void chooseProvider(int type, Key key, SecureRandom random)
		throws InvalidKeyException {
	    synchronized (lock) {
		if (sigSpi != null) {
		    init(sigSpi, type, key, random);
		    return;
		}
		Exception lastException = null;
		while ((firstService != null) || serviceIterator.hasNext()) {
		    Service s;
		    if (firstService != null) {
			s = firstService;
			firstService = null;
		    } else {
			s = (Service)serviceIterator.next();
		    }
		    // if provider says it does not support this key, ignore it
		    if (s.supportsParameter(key) == false) {
			continue;
		    }
		    // if instance is not a SignatureSpi, ignore it
		    if (isSpi(s) == false) {
			continue;
		    }
		    try {
			SignatureSpi spi = newInstance(s);
			init(spi, type, key, random);
			provider = s.getProvider();
			sigSpi = spi;
			firstService = null;
			serviceIterator = null;
			return;
		    } catch (Exception e) {
			// NoSuchAlgorithmException from newInstance()
			// InvalidKeyException from init()
			// RuntimeException (ProviderException) from init()
			if (lastException == null) {
			    lastException = e;
			}
		    }
		}
		// no working provider found, fail
		if (lastException instanceof InvalidKeyException) {
		    throw (InvalidKeyException)lastException;
		}
		if (lastException instanceof RuntimeException) {
		    throw (RuntimeException)lastException;
		}
		String k = (key != null) ? key.getClass().getName() : "(null)";
		throw new InvalidKeyException
		    ("No installed provider supports this key: "
		    + k, lastException);
	    }
	}

	private final static int I_PUB     = 1;
	private final static int I_PRIV    = 2;
	private final static int I_PRIV_SR = 3;
	
	private void init(SignatureSpi spi, int type, Key  key, 
		SecureRandom random) throws InvalidKeyException {
	    switch (type) {
	    case I_PUB:
		spi.engineInitVerify((PublicKey)key);
		break;
	    case I_PRIV:
		spi.engineInitSign((PrivateKey)key);
		break;
	    case I_PRIV_SR:
		spi.engineInitSign((PrivateKey)key, random);
		break;
	    default:
		throw new AssertionError("Internal error: " + type);
	    }
	}
	
	protected void engineInitVerify(PublicKey publicKey)
	    	throws InvalidKeyException {
	    if (sigSpi != null) {
		sigSpi.engineInitVerify(publicKey);
	    } else {
		chooseProvider(I_PUB, publicKey, null);
	    }
	}
	
	protected void engineInitSign(PrivateKey privateKey)
	    	throws InvalidKeyException {
	    if (sigSpi != null) {
		sigSpi.engineInitSign(privateKey);
	    } else {
		chooseProvider(I_PRIV, privateKey, null);
	    }
	}

        protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
            	throws InvalidKeyException {
	    if (sigSpi != null) {
		sigSpi.engineInitSign(privateKey, sr);
	    } else {
		chooseProvider(I_PRIV_SR, privateKey, sr);
	    }
        }

	protected void engineUpdate(byte b) throws SignatureException {
	    chooseFirstProvider();
	    sigSpi.engineUpdate(b);
	}

	protected void engineUpdate(byte[] b, int off, int len) 
	    	throws SignatureException {
	    chooseFirstProvider();
	    sigSpi.engineUpdate(b, off, len);
	}
	
	protected void engineUpdate(ByteBuffer data) {
	    chooseFirstProvider();
	    sigSpi.engineUpdate(data);
	}

	protected byte[] engineSign() throws SignatureException {
	    chooseFirstProvider();
	    return sigSpi.engineSign();
	}

	protected int engineSign(byte[] outbuf, int offset, int len)
	    	throws SignatureException {
	    chooseFirstProvider();
	    return sigSpi.engineSign(outbuf, offset, len);
	}

	protected boolean engineVerify(byte[] sigBytes) 
	    	throws SignatureException {
	    chooseFirstProvider();
	    return sigSpi.engineVerify(sigBytes);
	}

	protected boolean engineVerify(byte[] sigBytes, int offset, int length)
	    	throws SignatureException {
	    chooseFirstProvider();
	    return sigSpi.engineVerify(sigBytes, offset, length);
	}

	protected void engineSetParameter(String param, Object value) 
	    	throws InvalidParameterException {
	    chooseFirstProvider();
	    sigSpi.engineSetParameter(param, value);
	}

	protected void engineSetParameter(AlgorithmParameterSpec params)
	    	throws InvalidAlgorithmParameterException {
	    chooseFirstProvider();
	    sigSpi.engineSetParameter(params);
	}

	protected Object engineGetParameter(String param)
		throws InvalidParameterException {
	    chooseFirstProvider();
	    return sigSpi.engineGetParameter(param);
	}

	protected AlgorithmParameters engineGetParameters() {
	    chooseFirstProvider();
	    return sigSpi.engineGetParameters();
	}
    }

    // adapter for RSA/ECB/PKCS1Padding ciphers
    private static class CipherAdapter extends SignatureSpi {
	
	private final Cipher cipher;
	
	private ByteArrayOutputStream data;
	
	CipherAdapter(Cipher cipher) {
	    this.cipher = cipher;
	}
	
	protected void engineInitVerify(PublicKey publicKey) 
		throws InvalidKeyException {
	    cipher.init(Cipher.DECRYPT_MODE, publicKey);
	    if (data == null) {
		data = new ByteArrayOutputStream(128);
	    } else {
		data.reset();
	    }
	}

	protected void engineInitSign(PrivateKey privateKey) 
		throws InvalidKeyException {
	    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
	    data = null;
	}
	
	protected void engineInitSign(PrivateKey privateKey, 
		SecureRandom random) throws InvalidKeyException {
	    cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
	    data = null;
	}

	protected void engineUpdate(byte b) throws SignatureException {
	    engineUpdate(new byte[] {b}, 0, 1);
	}

	protected void engineUpdate(byte[] b, int off, int len) 
		throws SignatureException {
	    if (data != null) {
		data.write(b, off, len);
		return;
	    }
	    byte[] out = cipher.update(b, off, len);
	    if ((out != null) && (out.length != 0)) {
		throw new SignatureException
		    ("Cipher unexpectedly returned data");
	    }
	}
	
	protected byte[] engineSign() throws SignatureException {
	    try {
		return cipher.doFinal();
	    } catch (IllegalBlockSizeException e) {
		throw new SignatureException("doFinal() failed", e);
	    } catch (BadPaddingException e) {
		throw new SignatureException("doFinal() failed", e);
	    }
	}

	protected boolean engineVerify(byte[] sigBytes) 
		throws SignatureException {
	    try {
		byte[] out = cipher.doFinal(sigBytes);
		byte[] dataBytes = data.toByteArray();
		data.reset();
		return Arrays.equals(out, dataBytes);
	    } catch (BadPaddingException e) {
		// e.g. wrong public key used
		// return false rather than throwing exception
		return false;
	    } catch (IllegalBlockSizeException e) {
		throw new SignatureException("doFinal() failed", e);
	    }
	}

	protected void engineSetParameter(String param, Object value) 
		throws InvalidParameterException {
	    throw new InvalidParameterException("Parameters not supported");
	}

	protected Object engineGetParameter(String param) 
		throws InvalidParameterException {
	    throw new InvalidParameterException("Parameters not supported");
	}
	
    }

}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar