1 /*
2  * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  *
5  *
6  *
7  *
8  *
9  *
10  *
11  *
12  *
13  *
14  *
15  *
16  *
17  *
18  *
19  *
20  *
21  *
22  *
23  *
24  */

25
26 package java.security;
27
28 import java.security.spec.AlgorithmParameterSpec;
29 import java.util.*;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.io.*;
32 import java.security.cert.Certificate;
33 import java.security.cert.X509Certificate;
34
35 import java.nio.ByteBuffer;
36
37 import java.security.Provider.Service;
38
39 import javax.crypto.Cipher;
40 import javax.crypto.CipherSpi;
41 import javax.crypto.IllegalBlockSizeException;
42 import javax.crypto.BadPaddingException;
43 import javax.crypto.NoSuchPaddingException;
44
45 import sun.security.util.Debug;
46 import sun.security.jca.*;
47 import sun.security.jca.GetInstance.Instance;
48
49 /**
50  * The Signature class is used to provide applications the functionality
51  * of a digital signature algorithm. Digital signatures are used for
52  * authentication and integrity assurance of digital data.
53  *
54  * <p> The signature algorithm can be, among others, the NIST standard
55  * DSA, using DSA and SHA-1. The DSA algorithm using the
56  * SHA-1 message digest algorithm can be specified as {@code SHA1withDSA}.
57  * In the case of RSA, there are multiple choices for the message digest
58  * algorithm, so the signing algorithm could be specified as, for example,
59  * {@code MD2withRSA}, {@code MD5withRSA}, or {@code SHA1withRSA}.
60  * The algorithm name must be specified, as there is no default.
61  *
62  * <p> A Signature object can be used to generate and verify digital
63  * signatures.
64  *
65  * <p> There are three phases to the use of a Signature object for
66  * either signing data or verifying a signature:<ol>
67  *
68  * <li>Initialization, with either
69  *
70  *     <ul>
71  *
72  *     <li>a public key, which initializes the signature for
73  *     verification (see {@link #initVerify(PublicKey) initVerify}), or
74  *
75  *     <li>a private key (and optionally a Secure Random Number Generator),
76  *     which initializes the signature for signing
77  *     (see {@link #initSign(PrivateKey)}
78  *     and {@link #initSign(PrivateKey, SecureRandom)}).
79  *
80  *     </ul>
81  *
82  * <li>Updating
83  *
84  * <p>Depending on the type of initialization, this will update the
85  * bytes to be signed or verified. See the
86  * {@link #update(byte) update} methods.
87  *
88  * <li>Signing or Verifying a signature on all updated bytes. See the
89  * {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
90  * method.
91  *
92  * </ol>
93  *
94  * <p>Note that this class is abstract and extends from
95  * {@code SignatureSpi} for historical reasons.
96  * Application developers should only take notice of the methods defined in
97  * this {@code Signature} class; all the methods in
98  * the superclass are intended for cryptographic service providers who wish to
99  * supply their own implementations of digital signature algorithms.
100  *
101  * <p> Every implementation of the Java platform is required to support the
102  * following standard {@code Signature} algorithms:
103  * <ul>
104  * <li>{@code SHA1withDSA}</li>
105  * <li>{@code SHA1withRSA}</li>
106  * <li>{@code SHA256withRSA}</li>
107  * </ul>
108  * These algorithms are described in the <a href=
109  * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
110  * Signature section</a> of the
111  * Java Cryptography Architecture Standard Algorithm Name Documentation.
112  * Consult the release documentation for your implementation to see if any
113  * other algorithms are supported.
114  *
115  * @author Benjamin Renaud
116  *
117  */

118
119 public abstract class Signature extends SignatureSpi {
120
121     private static final Debug debug =
122                         Debug.getInstance("jca""Signature");
123
124     private static final Debug pdebug =
125                         Debug.getInstance("provider""Provider");
126     private static final boolean skipDebug =
127         Debug.isOn("engine=") && !Debug.isOn("signature");
128
129     /*
130      * The algorithm for this signature object.
131      * This value is used to map an OID to the particular algorithm.
132      * The mapping is done in AlgorithmObject.algOID(String algorithm)
133      */

134     private String algorithm;
135
136     // The provider
137     Provider provider;
138
139     /**
140      * Possible {@link #state} value, signifying that
141      * this signature object has not yet been initialized.
142      */

143     protected final static int UNINITIALIZED = 0;
144
145     /**
146      * Possible {@link #state} value, signifying that
147      * this signature object has been initialized for signing.
148      */

149     protected final static int SIGN = 2;
150
151     /**
152      * Possible {@link #state} value, signifying that
153      * this signature object has been initialized for verification.
154      */

155     protected final static int VERIFY = 3;
156
157     /**
158      * Current state of this signature object.
159      */

160     protected int state = UNINITIALIZED;
161
162     /**
163      * Creates a Signature object for the specified algorithm.
164      *
165      * @param algorithm the standard string name of the algorithm.
166      * See the Signature section in the <a href=
167      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
168      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
169      * for information about standard algorithm names.
170      */

171     protected Signature(String algorithm) {
172         this.algorithm = algorithm;
173     }
174
175     // name of the special signature alg
176     private final static String RSA_SIGNATURE = "NONEwithRSA";
177
178     // name of the equivalent cipher alg
179     private final static String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
180
181     // all the services we need to lookup for compatibility with Cipher
182     private final static List<ServiceId> rsaIds = Arrays.asList(
183         new ServiceId[] {
184             new ServiceId("Signature""NONEwithRSA"),
185             new ServiceId("Cipher""RSA/ECB/PKCS1Padding"),
186             new ServiceId("Cipher""RSA/ECB"),
187             new ServiceId("Cipher""RSA//PKCS1Padding"),
188             new ServiceId("Cipher""RSA"),
189         }
190     );
191
192     /**
193      * Returns a Signature object that implements the specified signature
194      * algorithm.
195      *
196      * <p> This method traverses the list of registered security Providers,
197      * starting with the most preferred Provider.
198      * A new Signature object encapsulating the
199      * SignatureSpi implementation from the first
200      * Provider that supports the specified algorithm is returned.
201      *
202      * <p> Note that the list of registered providers may be retrieved via
203      * the {@link Security#getProviders() Security.getProviders()} method.
204      *
205      * @param algorithm the standard name of the algorithm requested.
206      * See the Signature section in the <a href=
207      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
208      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
209      * for information about standard algorithm names.
210      *
211      * @return the new Signature object.
212      *
213      * @exception NoSuchAlgorithmException if no Provider supports a
214      *          Signature implementation for the
215      *          specified algorithm.
216      *
217      * @see Provider
218      */

219     public static Signature getInstance(String algorithm)
220             throws NoSuchAlgorithmException {
221         List<Service> list;
222         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
223             list = GetInstance.getServices(rsaIds);
224         } else {
225             list = GetInstance.getServices("Signature", algorithm);
226         }
227         Iterator<Service> t = list.iterator();
228         if (t.hasNext() == false) {
229             throw new NoSuchAlgorithmException
230                 (algorithm + " Signature not available");
231         }
232         // try services until we find an Spi or a working Signature subclass
233         NoSuchAlgorithmException failure;
234         do {
235             Service s = t.next();
236             if (isSpi(s)) {
237                 return new Delegate(s, t, algorithm);
238             } else {
239                 // must be a subclass of Signature, disable dynamic selection
240                 try {
241                     Instance instance =
242                         GetInstance.getInstance(s, SignatureSpi.class);
243                     return getInstance(instance, algorithm);
244                 } catch (NoSuchAlgorithmException e) {
245                     failure = e;
246                 }
247             }
248         } while (t.hasNext());
249         throw failure;
250     }
251
252     private static Signature getInstance(Instance instance, String algorithm) {
253         Signature sig;
254         if (instance.impl instanceof Signature) {
255             sig = (Signature)instance.impl;
256             sig.algorithm = algorithm;
257         } else {
258             SignatureSpi spi = (SignatureSpi)instance.impl;
259             sig = new Delegate(spi, algorithm);
260         }
261         sig.provider = instance.provider;
262         return sig;
263     }
264
265     private final static Map<String,Boolean> signatureInfo;
266
267     static {
268         signatureInfo = new ConcurrentHashMap<String,Boolean>();
269         Boolean TRUE = Boolean.TRUE;
270         // pre-initialize with values for our SignatureSpi implementations
271         signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
272         signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
273         signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
274         signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
275         signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
276         signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
277         signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
278         signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
279         signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
280         signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
281     }
282
283     private static boolean isSpi(Service s) {
284         if (s.getType().equals("Cipher")) {
285             // must be a CipherSpi, which we can wrap with the CipherAdapter
286             return true;
287         }
288         String className = s.getClassName();
289         Boolean result = signatureInfo.get(className);
290         if (result == null) {
291             try {
292                 Object instance = s.newInstance(null);
293                 // Signature extends SignatureSpi
294                 // so it is a "real" Spi if it is an
295                 // instance of SignatureSpi but not Signature
296                 boolean r = (instance instanceof SignatureSpi)
297                                 && (instance instanceof Signature == false);
298                 if ((debug != null) && (r == false)) {
299                     debug.println("Not a SignatureSpi " + className);
300                     debug.println("Delayed provider selection may not be "
301                         + "available for algorithm " + s.getAlgorithm());
302                 }
303                 result = Boolean.valueOf(r);
304                 signatureInfo.put(className, result);
305             } catch (Exception e) {
306                 // something is wrong, assume not an SPI
307                 return false;
308             }
309         }
310         return result.booleanValue();
311     }
312
313     /**
314      * Returns a Signature object that implements the specified signature
315      * algorithm.
316      *
317      * <p> A new Signature object encapsulating the
318      * SignatureSpi implementation from the specified provider
319      * is returned.  The specified provider must be registered
320      * in the security provider list.
321      *
322      * <p> Note that the list of registered providers may be retrieved via
323      * the {@link Security#getProviders() Security.getProviders()} method.
324      *
325      * @param algorithm the name of the algorithm requested.
326      * See the Signature section in the <a href=
327      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
328      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
329      * for information about standard algorithm names.
330      *
331      * @param provider the name of the provider.
332      *
333      * @return the new Signature object.
334      *
335      * @exception NoSuchAlgorithmException if a SignatureSpi
336      *          implementation for the specified algorithm is not
337      *          available from the specified provider.
338      *
339      * @exception NoSuchProviderException if the specified provider is not
340      *          registered in the security provider list.
341      *
342      * @exception IllegalArgumentException if the provider name is null
343      *          or empty.
344      *
345      * @see Provider
346      */

347     public static Signature getInstance(String algorithm, String provider)
348             throws NoSuchAlgorithmException, NoSuchProviderException {
349         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
350             // exception compatibility with existing code
351             if ((provider == null) || (provider.length() == 0)) {
352                 throw new IllegalArgumentException("missing provider");
353             }
354             Provider p = Security.getProvider(provider);
355             if (p == null) {
356                 throw new NoSuchProviderException
357                     ("no such provider: " + provider);
358             }
359             return getInstanceRSA(p);
360         }
361         Instance instance = GetInstance.getInstance
362                 ("Signature", SignatureSpi.class, algorithm, provider);
363         return getInstance(instance, algorithm);
364     }
365
366     /**
367      * Returns a Signature object that implements the specified
368      * signature algorithm.
369      *
370      * <p> A new Signature object encapsulating the
371      * SignatureSpi implementation from the specified Provider
372      * object is returned.  Note that the specified Provider object
373      * does not have to be registered in the provider list.
374      *
375      * @param algorithm the name of the algorithm requested.
376      * See the Signature section in the <a href=
377      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
378      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
379      * for information about standard algorithm names.
380      *
381      * @param provider the provider.
382      *
383      * @return the new Signature object.
384      *
385      * @exception NoSuchAlgorithmException if a SignatureSpi
386      *          implementation for the specified algorithm is not available
387      *          from the specified Provider object.
388      *
389      * @exception IllegalArgumentException if the provider is null.
390      *
391      * @see Provider
392      *
393      * @since 1.4
394      */

395     public static Signature getInstance(String algorithm, Provider provider)
396             throws NoSuchAlgorithmException {
397         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
398             // exception compatibility with existing code
399             if (provider == null) {
400                 throw new IllegalArgumentException("missing provider");
401             }
402             return getInstanceRSA(provider);
403         }
404         Instance instance = GetInstance.getInstance
405                 ("Signature", SignatureSpi.class, algorithm, provider);
406         return getInstance(instance, algorithm);
407     }
408
409     // return an implementation for NONEwithRSA, which is a special case
410     // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
411     private static Signature getInstanceRSA(Provider p)
412             throws NoSuchAlgorithmException {
413         // try Signature first
414         Service s = p.getService("Signature", RSA_SIGNATURE);
415         if (s != null) {
416             Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
417             return getInstance(instance, RSA_SIGNATURE);
418         }
419         // check Cipher
420         try {
421             Cipher c = Cipher.getInstance(RSA_CIPHER, p);
422             return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
423         } catch (GeneralSecurityException e) {
424             // throw Signature style exception message to avoid confusion,
425             // but append Cipher exception as cause
426             throw new NoSuchAlgorithmException("no such algorithm: "
427                 + RSA_SIGNATURE + for provider " + p.getName(), e);
428         }
429     }
430
431     /**
432      * Returns the provider of this signature object.
433      *
434      * @return the provider of this signature object
435      */

436     public final Provider getProvider() {
437         chooseFirstProvider();
438         return this.provider;
439     }
440
441     private String getProviderName() {
442         return (provider == null)  ? "(no provider)" : provider.getName();
443     }
444
445     void chooseFirstProvider() {
446         // empty, overridden in Delegate
447     }
448
449     /**
450      * Initializes this object for verification. If this method is called
451      * again with a different argument, it negates the effect
452      * of this call.
453      *
454      * @param publicKey the public key of the identity whose signature is
455      * going to be verified.
456      *
457      * @exception InvalidKeyException if the key is invalid.
458      */

459     public final void initVerify(PublicKey publicKey)
460             throws InvalidKeyException {
461         engineInitVerify(publicKey);
462         state = VERIFY;
463
464         if (!skipDebug && pdebug != null) {
465             pdebug.println("Signature." + algorithm +
466                 " verification algorithm from: " + getProviderName());
467         }
468     }
469
470     /**
471      * Initializes this object for verification, using the public key from
472      * the given certificate.
473      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
474      * extension field marked as critical, and the value of the <i>key usage</i>
475      * extension field implies that the public key in
476      * the certificate and its corresponding private key are not
477      * supposed to be used for digital signatures, an
478      * {@code InvalidKeyException} is thrown.
479      *
480      * @param certificate the certificate of the identity whose signature is
481      * going to be verified.
482      *
483      * @exception InvalidKeyException  if the public key in the certificate
484      * is not encoded properly or does not include required  parameter
485      * information or cannot be used for digital signature purposes.
486      * @since 1.3
487      */

488     public final void initVerify(Certificate certificate)
489             throws InvalidKeyException {
490         // If the certificate is of type X509Certificate,
491         // we should check whether it has a Key Usage
492         // extension marked as critical.
493         if (certificate instanceof java.security.cert.X509Certificate) {
494             // Check whether the cert has a key usage extension
495             // marked as a critical extension.
496             // The OID for KeyUsage extension is 2.5.29.15.
497             X509Certificate cert = (X509Certificate)certificate;
498             Set<String> critSet = cert.getCriticalExtensionOIDs();
499
500             if (critSet != null && !critSet.isEmpty()
501                 && critSet.contains("2.5.29.15")) {
502                 boolean[] keyUsageInfo = cert.getKeyUsage();
503                 // keyUsageInfo[0] is for digitalSignature.
504                 if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
505                     throw new InvalidKeyException("Wrong key usage");
506             }
507         }
508
509         PublicKey publicKey = certificate.getPublicKey();
510         engineInitVerify(publicKey);
511         state = VERIFY;
512
513         if (!skipDebug && pdebug != null) {
514             pdebug.println("Signature." + algorithm +
515                 " verification algorithm from: " + getProviderName());
516         }
517     }
518
519     /**
520      * Initialize this object for signing. If this method is called
521      * again with a different argument, it negates the effect
522      * of this call.
523      *
524      * @param privateKey the private key of the identity whose signature
525      * is going to be generated.
526      *
527      * @exception InvalidKeyException if the key is invalid.
528      */

529     public final void initSign(PrivateKey privateKey)
530             throws InvalidKeyException {
531         engineInitSign(privateKey);
532         state = SIGN;
533
534         if (!skipDebug && pdebug != null) {
535             pdebug.println("Signature." + algorithm +
536                 " signing algorithm from: " + getProviderName());
537         }
538     }
539
540     /**
541      * Initialize this object for signing. If this method is called
542      * again with a different argument, it negates the effect
543      * of this call.
544      *
545      * @param privateKey the private key of the identity whose signature
546      * is going to be generated.
547      *
548      * @param random the source of randomness for this signature.
549      *
550      * @exception InvalidKeyException if the key is invalid.
551      */

552     public final void initSign(PrivateKey privateKey, SecureRandom random)
553             throws InvalidKeyException {
554         engineInitSign(privateKey, random);
555         state = SIGN;
556
557         if (!skipDebug && pdebug != null) {
558             pdebug.println("Signature." + algorithm +
559                 " signing algorithm from: " + getProviderName());
560         }
561     }
562
563     /**
564      * Returns the signature bytes of all the data updated.
565      * The format of the signature depends on the underlying
566      * signature scheme.
567      *
568      * <p>A call to this method resets this signature object to the state
569      * it was in when previously initialized for signing via a
570      * call to {@code initSign(PrivateKey)}. That is, the object is
571      * reset and available to generate another signature from the same
572      * signer, if desired, via new calls to {@code update} and
573      * {@code sign}.
574      *
575      * @return the signature bytes of the signing operation's result.
576      *
577      * @exception SignatureException if this signature object is not
578      * initialized properly or if this signature algorithm is unable to
579      * process the input data provided.
580      */

581     public final byte[] sign() throws SignatureException {
582         if (state == SIGN) {
583             return engineSign();
584         }
585         throw new SignatureException("object not initialized for " +
586                                      "signing");
587     }
588
589     /**
590      * Finishes the signature operation and stores the resulting signature
591      * bytes in the provided buffer {@code outbuf}, starting at
592      * {@code offset}.
593      * The format of the signature depends on the underlying
594      * signature scheme.
595      *
596      * <p>This signature object is reset to its initial state (the state it
597      * was in after a call to one of the {@code initSign} methods) and
598      * can be reused to generate further signatures with the same private key.
599      *
600      * @param outbuf buffer for the signature result.
601      *
602      * @param offset offset into {@code outbuf} where the signature is
603      * stored.
604      *
605      * @param len number of bytes within {@code outbuf} allotted for the
606      * signature.
607      *
608      * @return the number of bytes placed into {@code outbuf}.
609      *
610      * @exception SignatureException if this signature object is not
611      * initialized properly, if this signature algorithm is unable to
612      * process the input data provided, or if {@code len} is less
613      * than the actual signature length.
614      *
615      * @since 1.2
616      */

617     public final int sign(byte[] outbuf, int offset, int len)
618         throws SignatureException {
619         if (outbuf == null) {
620             throw new IllegalArgumentException("No output buffer given");
621         }
622         if (offset < 0 || len < 0) {
623             throw new IllegalArgumentException("offset or len is less than 0");
624         }
625         if (outbuf.length - offset < len) {
626             throw new IllegalArgumentException
627                 ("Output buffer too small for specified offset and length");
628         }
629         if (state != SIGN) {
630             throw new SignatureException("object not initialized for " +
631                                          "signing");
632         }
633         return engineSign(outbuf, offset, len);
634     }
635
636     /**
637      * Verifies the passed-in signature.
638      *
639      * <p>A call to this method resets this signature object to the state
640      * it was in when previously initialized for verification via a
641      * call to {@code initVerify(PublicKey)}. That is, the object is
642      * reset and available to verify another signature from the identity
643      * whose public key was specified in the call to {@code initVerify}.
644      *
645      * @param signature the signature bytes to be verified.
646      *
647      * @return true if the signature was verified, false if not.
648      *
649      * @exception SignatureException if this signature object is not
650      * initialized properly, the passed-in signature is improperly
651      * encoded or of the wrong type, if this signature algorithm is unable to
652      * process the input data provided, etc.
653      */

654     public final boolean verify(byte[] signature) throws SignatureException {
655         if (state == VERIFY) {
656             return engineVerify(signature);
657         }
658         throw new SignatureException("object not initialized for " +
659                                      "verification");
660     }
661
662     /**
663      * Verifies the passed-in signature in the specified array
664      * of bytes, starting at the specified offset.
665      *
666      * <p>A call to this method resets this signature object to the state
667      * it was in when previously initialized for verification via a
668      * call to {@code initVerify(PublicKey)}. That is, the object is
669      * reset and available to verify another signature from the identity
670      * whose public key was specified in the call to {@code initVerify}.
671      *
672      *
673      * @param signature the signature bytes to be verified.
674      * @param offset the offset to start from in the array of bytes.
675      * @param length the number of bytes to use, starting at offset.
676      *
677      * @return true if the signature was verified, false if not.
678      *
679      * @exception SignatureException if this signature object is not
680      * initialized properly, the passed-in signature is improperly
681      * encoded or of the wrong type, if this signature algorithm is unable to
682      * process the input data provided, etc.
683      * @exception IllegalArgumentException if the {@code signature}
684      * byte array is null, or the {@code offset} or {@code length}
685      * is less than 0, or the sum of the {@code offset} and
686      * {@code length} is greater than the length of the
687      * {@code signature} byte array.
688      * @since 1.4
689      */

690     public final boolean verify(byte[] signature, int offset, int length)
691         throws SignatureException {
692         if (state == VERIFY) {
693             if (signature == null) {
694                 throw new IllegalArgumentException("signature is null");
695             }
696             if (offset < 0 || length < 0) {
697                 throw new IllegalArgumentException
698                     ("offset or length is less than 0");
699             }
700             if (signature.length - offset < length) {
701                 throw new IllegalArgumentException
702                     ("signature too small for specified offset and length");
703             }
704
705             return engineVerify(signature, offset, length);
706         }
707         throw new SignatureException("object not initialized for " +
708                                      "verification");
709     }
710
711     /**
712      * Updates the data to be signed or verified by a byte.
713      *
714      * @param b the byte to use for the update.
715      *
716      * @exception SignatureException if this signature object is not
717      * initialized properly.
718      */

719     public final void update(byte b) throws SignatureException {
720         if (state == VERIFY || state == SIGN) {
721             engineUpdate(b);
722         } else {
723             throw new SignatureException("object not initialized for "
724                                          + "signature or verification");
725         }
726     }
727
728     /**
729      * Updates the data to be signed or verified, using the specified
730      * array of bytes.
731      *
732      * @param data the byte array to use for the update.
733      *
734      * @exception SignatureException if this signature object is not
735      * initialized properly.
736      */

737     public final void update(byte[] data) throws SignatureException {
738         update(data, 0, data.length);
739     }
740
741     /**
742      * Updates the data to be signed or verified, using the specified
743      * array of bytes, starting at the specified offset.
744      *
745      * @param data the array of bytes.
746      * @param off the offset to start from in the array of bytes.
747      * @param len the number of bytes to use, starting at offset.
748      *
749      * @exception SignatureException if this signature object is not
750      * initialized properly.
751      */

752     public final void update(byte[] data, int off, int len)
753             throws SignatureException {
754         if (state == SIGN || state == VERIFY) {
755             if (data == null) {
756                 throw new IllegalArgumentException("data is null");
757             }
758             if (off < 0 || len < 0) {
759                 throw new IllegalArgumentException("off or len is less than 0");
760             }
761             if (data.length - off < len) {
762                 throw new IllegalArgumentException
763                     ("data too small for specified offset and length");
764             }
765             engineUpdate(data, off, len);
766         } else {
767             throw new SignatureException("object not initialized for "
768                                          + "signature or verification");
769         }
770     }
771
772     /**
773      * Updates the data to be signed or verified using the specified
774      * ByteBuffer. Processes the {@code data.remaining()} bytes
775      * starting at at {@code data.position()}.
776      * Upon return, the buffer's position will be equal to its limit;
777      * its limit will not have changed.
778      *
779      * @param data the ByteBuffer
780      *
781      * @exception SignatureException if this signature object is not
782      * initialized properly.
783      * @since 1.5
784      */

785     public final void update(ByteBuffer data) throws SignatureException {
786         if ((state != SIGN) && (state != VERIFY)) {
787             throw new SignatureException("object not initialized for "
788                                          + "signature or verification");
789         }
790         if (data == null) {
791             throw new NullPointerException();
792         }
793         engineUpdate(data);
794     }
795
796     /**
797      * Returns the name of the algorithm for this signature object.
798      *
799      * @return the name of the algorithm for this signature object.
800      */

801     public final String getAlgorithm() {
802         return this.algorithm;
803     }
804
805     /**
806      * Returns a string representation of this signature object,
807      * providing information that includes the state of the object
808      * and the name of the algorithm used.
809      *
810      * @return a string representation of this signature object.
811      */

812     public String toString() {
813         String initState = "";
814         switch (state) {
815         case UNINITIALIZED:
816             initState = "<not initialized>";
817             break;
818         case VERIFY:
819             initState = "<initialized for verifying>";
820             break;
821         case SIGN:
822             initState = "<initialized for signing>";
823             break;
824         }
825         return "Signature object: " + getAlgorithm() + initState;
826     }
827
828     /**
829      * Sets the specified algorithm parameter to the specified value.
830      * This method supplies a general-purpose mechanism through
831      * which it is possible to set the various parameters of this object.
832      * A parameter may be any settable parameter for the algorithm, such as
833      * a parameter size, or a source of random bits for signature generation
834      * (if appropriate), or an indication of whether or not to perform
835      * a specific but optional computation. A uniform algorithm-specific
836      * naming scheme for each parameter is desirable but left unspecified
837      * at this time.
838      *
839      * @param param the string identifier of the parameter.
840      * @param value the parameter value.
841      *
842      * @exception InvalidParameterException if {@code param} is an
843      * invalid parameter for this signature algorithm engine,
844      * the parameter is already set
845      * and cannot be set again, a security exception occurs, and so on.
846      *
847      * @see #getParameter
848      *
849      * @deprecated Use
850      * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
851      * setParameter}.
852      */

853     @Deprecated
854     public final void setParameter(String param, Object value)
855             throws InvalidParameterException {
856         engineSetParameter(param, value);
857     }
858
859     /**
860      * Initializes this signature engine with the specified parameter set.
861      *
862      * @param params the parameters
863      *
864      * @exception InvalidAlgorithmParameterException if the given parameters
865      * are inappropriate for this signature engine
866      *
867      * @see #getParameters
868      */

869     public final void setParameter(AlgorithmParameterSpec params)
870             throws InvalidAlgorithmParameterException {
871         engineSetParameter(params);
872     }
873
874     /**
875      * Returns the parameters used with this signature object.
876      *
877      * <p>The returned parameters may be the same that were used to initialize
878      * this signature, or may contain a combination of default and randomly
879      * generated parameter values used by the underlying signature
880      * implementation if this signature requires algorithm parameters but
881      * was not initialized with any.
882      *
883      * @return the parameters used with this signature, or null if this
884      * signature does not use any parameters.
885      *
886      * @see #setParameter(AlgorithmParameterSpec)
887      * @since 1.4
888      */

889     public final AlgorithmParameters getParameters() {
890         return engineGetParameters();
891     }
892
893     /**
894      * Gets the value of the specified algorithm parameter. This method
895      * supplies a general-purpose mechanism through which it is possible to
896      * get the various parameters of this object. A parameter may be any
897      * settable parameter for the algorithm, such as a parameter size, or
898      * a source of random bits for signature generation (if appropriate),
899      * or an indication of whether or not to perform a specific but optional
900      * computation. A uniform algorithm-specific naming scheme for each
901      * parameter is desirable but left unspecified at this time.
902      *
903      * @param param the string name of the parameter.
904      *
905      * @return the object that represents the parameter value, or null if
906      * there is none.
907      *
908      * @exception InvalidParameterException if {@code param} is an invalid
909      * parameter for this engine, or another exception occurs while
910      * trying to get this parameter.
911      *
912      * @see #setParameter(String, Object)
913      *
914      * @deprecated
915      */

916     @Deprecated
917     public final Object getParameter(String param)
918             throws InvalidParameterException {
919         return engineGetParameter(param);
920     }
921
922     /**
923      * Returns a clone if the implementation is cloneable.
924      *
925      * @return a clone if the implementation is cloneable.
926      *
927      * @exception CloneNotSupportedException if this is called
928      * on an implementation that does not support {@code Cloneable}.
929      */

930     public Object clone() throws CloneNotSupportedException {
931         if (this instanceof Cloneable) {
932             return super.clone();
933         } else {
934             throw new CloneNotSupportedException();
935         }
936     }
937
938     /*
939      * The following class allows providers to extend from SignatureSpi
940      * rather than from Signature. It represents a Signature with an
941      * encapsulated, provider-supplied SPI object (of type SignatureSpi).
942      * If the provider implementation is an instance of SignatureSpi, the
943      * getInstance() methods above return an instance of this class, with
944      * the SPI object encapsulated.
945      *
946      * Note: All SPI methods from the original Signature class have been
947      * moved up the hierarchy into a new class (SignatureSpi), which has
948      * been interposed in the hierarchy between the API (Signature)
949      * and its original parent (Object).
950      */

951
952     @SuppressWarnings("deprecation")
953     private static class Delegate extends Signature {
954
955         // The provider implementation (delegate)
956         // filled in once the provider is selected
957         private SignatureSpi sigSpi;
958
959         // lock for mutex during provider selection
960         private final Object lock;
961
962         // next service to try in provider selection
963         // null once provider is selected
964         private Service firstService;
965
966         // remaining services to try in provider selection
967         // null once provider is selected
968         private Iterator<Service> serviceIterator;
969
970         // constructor
971         Delegate(SignatureSpi sigSpi, String algorithm) {
972             super(algorithm);
973             this.sigSpi = sigSpi;
974             this.lock = null// no lock needed
975         }
976
977         // used with delayed provider selection
978         Delegate(Service service,
979                         Iterator<Service> iterator, String algorithm) {
980             super(algorithm);
981             this.firstService = service;
982             this.serviceIterator = iterator;
983             this.lock = new Object();
984         }
985
986         /**
987          * Returns a clone if the delegate is cloneable.
988          *
989          * @return a clone if the delegate is cloneable.
990          *
991          * @exception CloneNotSupportedException if this is called on a
992          * delegate that does not support {@code Cloneable}.
993          */

994         public Object clone() throws CloneNotSupportedException {
995             chooseFirstProvider();
996             if (sigSpi instanceof Cloneable) {
997                 SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
998                 // Because 'algorithm' and 'provider' are private
999                 // members of our supertype, we must perform a cast to
1000                 // access them.
1001                 Signature that =
1002                     new Delegate(sigSpiClone, ((Signature)this).algorithm);
1003                 that.provider = ((Signature)this).provider;
1004                 return that;
1005             } else {
1006                 throw new CloneNotSupportedException();
1007             }
1008         }
1009
1010         private static SignatureSpi newInstance(Service s)
1011                 throws NoSuchAlgorithmException {
1012             if (s.getType().equals("Cipher")) {
1013                 // must be NONEwithRSA
1014                 try {
1015                     Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
1016                     return new CipherAdapter(c);
1017                 } catch (NoSuchPaddingException e) {
1018                     throw new NoSuchAlgorithmException(e);
1019                 }
1020             } else {
1021                 Object o = s.newInstance(null);
1022                 if (o instanceof SignatureSpi == false) {
1023                     throw new NoSuchAlgorithmException
1024                         ("Not a SignatureSpi: " + o.getClass().getName());
1025                 }
1026                 return (SignatureSpi)o;
1027             }
1028         }
1029
1030         // max number of debug warnings to print from chooseFirstProvider()
1031         private static int warnCount = 10;
1032
1033         /**
1034          * Choose the Spi from the first provider available. Used if
1035          * delayed provider selection is not possible because initSign()/
1036          * initVerify() is not the first method called.
1037          */

1038         void chooseFirstProvider() {
1039             if (sigSpi != null) {
1040                 return;
1041             }
1042             synchronized (lock) {
1043                 if (sigSpi != null) {
1044                     return;
1045                 }
1046                 if (debug != null) {
1047                     int w = --warnCount;
1048                     if (w >= 0) {
1049                         debug.println("Signature.init() not first method "
1050                             + "called, disabling delayed provider selection");
1051                         if (w == 0) {
1052                             debug.println("Further warnings of this type will "
1053                                 + "be suppressed");
1054                         }
1055                         new Exception("Call trace").printStackTrace();
1056                     }
1057                 }
1058                 Exception lastException = null;
1059                 while ((firstService != null) || serviceIterator.hasNext()) {
1060                     Service s;
1061                     if (firstService != null) {
1062                         s = firstService;
1063                         firstService = null;
1064                     } else {
1065                         s = serviceIterator.next();
1066                     }
1067                     if (isSpi(s) == false) {
1068                         continue;
1069                     }
1070                     try {
1071                         sigSpi = newInstance(s);
1072                         provider = s.getProvider();
1073                         // not needed any more
1074                         firstService = null;
1075                         serviceIterator = null;
1076                         return;
1077                     } catch (NoSuchAlgorithmException e) {
1078                         lastException = e;
1079                     }
1080                 }
1081                 ProviderException e = new ProviderException
1082                         ("Could not construct SignatureSpi instance");
1083                 if (lastException != null) {
1084                     e.initCause(lastException);
1085                 }
1086                 throw e;
1087             }
1088         }
1089
1090         private void chooseProvider(int type, Key key, SecureRandom random)
1091                 throws InvalidKeyException {
1092             synchronized (lock) {
1093                 if (sigSpi != null) {
1094                     init(sigSpi, type, key, random);
1095                     return;
1096                 }
1097                 Exception lastException = null;
1098                 while ((firstService != null) || serviceIterator.hasNext()) {
1099                     Service s;
1100                     if (firstService != null) {
1101                         s = firstService;
1102                         firstService = null;
1103                     } else {
1104                         s = serviceIterator.next();
1105                     }
1106                     // if provider says it does not support this key, ignore it
1107                     if (s.supportsParameter(key) == false) {
1108                         continue;
1109                     }
1110                     // if instance is not a SignatureSpi, ignore it
1111                     if (isSpi(s) == false) {
1112                         continue;
1113                     }
1114                     try {
1115                         SignatureSpi spi = newInstance(s);
1116                         init(spi, type, key, random);
1117                         provider = s.getProvider();
1118                         sigSpi = spi;
1119                         firstService = null;
1120                         serviceIterator = null;
1121                         return;
1122                     } catch (Exception e) {
1123                         // NoSuchAlgorithmException from newInstance()
1124                         // InvalidKeyException from init()
1125                         // RuntimeException (ProviderException) from init()
1126                         if (lastException == null) {
1127                             lastException = e;
1128                         }
1129                     }
1130                 }
1131                 // no working provider found, fail
1132                 if (lastException instanceof InvalidKeyException) {
1133                     throw (InvalidKeyException)lastException;
1134                 }
1135                 if (lastException instanceof RuntimeException) {
1136                     throw (RuntimeException)lastException;
1137                 }
1138                 String k = (key != null) ? key.getClass().getName() : "(null)";
1139                 throw new InvalidKeyException
1140                     ("No installed provider supports this key: "
1141                     + k, lastException);
1142             }
1143         }
1144
1145         private final static int I_PUB     = 1;
1146         private final static int I_PRIV    = 2;
1147         private final static int I_PRIV_SR = 3;
1148
1149         private void init(SignatureSpi spi, int type, Key  key,
1150                 SecureRandom random) throws InvalidKeyException {
1151             switch (type) {
1152             case I_PUB:
1153                 spi.engineInitVerify((PublicKey)key);
1154                 break;
1155             case I_PRIV:
1156                 spi.engineInitSign((PrivateKey)key);
1157                 break;
1158             case I_PRIV_SR:
1159                 spi.engineInitSign((PrivateKey)key, random);
1160                 break;
1161             default:
1162                 throw new AssertionError("Internal error: " + type);
1163             }
1164         }
1165
1166         protected void engineInitVerify(PublicKey publicKey)
1167                 throws InvalidKeyException {
1168             if (sigSpi != null) {
1169                 sigSpi.engineInitVerify(publicKey);
1170             } else {
1171                 chooseProvider(I_PUB, publicKey, null);
1172             }
1173         }
1174
1175         protected void engineInitSign(PrivateKey privateKey)
1176                 throws InvalidKeyException {
1177             if (sigSpi != null) {
1178                 sigSpi.engineInitSign(privateKey);
1179             } else {
1180                 chooseProvider(I_PRIV, privateKey, null);
1181             }
1182         }
1183
1184         protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
1185                 throws InvalidKeyException {
1186             if (sigSpi != null) {
1187                 sigSpi.engineInitSign(privateKey, sr);
1188             } else {
1189                 chooseProvider(I_PRIV_SR, privateKey, sr);
1190             }
1191         }
1192
1193         protected void engineUpdate(byte b) throws SignatureException {
1194             chooseFirstProvider();
1195             sigSpi.engineUpdate(b);
1196         }
1197
1198         protected void engineUpdate(byte[] b, int off, int len)
1199                 throws SignatureException {
1200             chooseFirstProvider();
1201             sigSpi.engineUpdate(b, off, len);
1202         }
1203
1204         protected void engineUpdate(ByteBuffer data) {
1205             chooseFirstProvider();
1206             sigSpi.engineUpdate(data);
1207         }
1208
1209         protected byte[] engineSign() throws SignatureException {
1210             chooseFirstProvider();
1211             return sigSpi.engineSign();
1212         }
1213
1214         protected int engineSign(byte[] outbuf, int offset, int len)
1215                 throws SignatureException {
1216             chooseFirstProvider();
1217             return sigSpi.engineSign(outbuf, offset, len);
1218         }
1219
1220         protected boolean engineVerify(byte[] sigBytes)
1221                 throws SignatureException {
1222             chooseFirstProvider();
1223             return sigSpi.engineVerify(sigBytes);
1224         }
1225
1226         protected boolean engineVerify(byte[] sigBytes, int offset, int length)
1227                 throws SignatureException {
1228             chooseFirstProvider();
1229             return sigSpi.engineVerify(sigBytes, offset, length);
1230         }
1231
1232         protected void engineSetParameter(String param, Object value)
1233                 throws InvalidParameterException {
1234             chooseFirstProvider();
1235             sigSpi.engineSetParameter(param, value);
1236         }
1237
1238         protected void engineSetParameter(AlgorithmParameterSpec params)
1239                 throws InvalidAlgorithmParameterException {
1240             chooseFirstProvider();
1241             sigSpi.engineSetParameter(params);
1242         }
1243
1244         protected Object engineGetParameter(String param)
1245                 throws InvalidParameterException {
1246             chooseFirstProvider();
1247             return sigSpi.engineGetParameter(param);
1248         }
1249
1250         protected AlgorithmParameters engineGetParameters() {
1251             chooseFirstProvider();
1252             return sigSpi.engineGetParameters();
1253         }
1254     }
1255
1256     // adapter for RSA/ECB/PKCS1Padding ciphers
1257     @SuppressWarnings("deprecation")
1258     private static class CipherAdapter extends SignatureSpi {
1259
1260         private final Cipher cipher;
1261
1262         private ByteArrayOutputStream data;
1263
1264         CipherAdapter(Cipher cipher) {
1265             this.cipher = cipher;
1266         }
1267
1268         protected void engineInitVerify(PublicKey publicKey)
1269                 throws InvalidKeyException {
1270             cipher.init(Cipher.DECRYPT_MODE, publicKey);
1271             if (data == null) {
1272                 data = new ByteArrayOutputStream(128);
1273             } else {
1274                 data.reset();
1275             }
1276         }
1277
1278         protected void engineInitSign(PrivateKey privateKey)
1279                 throws InvalidKeyException {
1280             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
1281             data = null;
1282         }
1283
1284         protected void engineInitSign(PrivateKey privateKey,
1285                 SecureRandom random) throws InvalidKeyException {
1286             cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
1287             data = null;
1288         }
1289
1290         protected void engineUpdate(byte b) throws SignatureException {
1291             engineUpdate(new byte[] {b}, 0, 1);
1292         }
1293
1294         protected void engineUpdate(byte[] b, int off, int len)
1295                 throws SignatureException {
1296             if (data != null) {
1297                 data.write(b, off, len);
1298                 return;
1299             }
1300             byte[] out = cipher.update(b, off, len);
1301             if ((out != null) && (out.length != 0)) {
1302                 throw new SignatureException
1303                     ("Cipher unexpectedly returned data");
1304             }
1305         }
1306
1307         protected byte[] engineSign() throws SignatureException {
1308             try {
1309                 return cipher.doFinal();
1310             } catch (IllegalBlockSizeException e) {
1311                 throw new SignatureException("doFinal() failed", e);
1312             } catch (BadPaddingException e) {
1313                 throw new SignatureException("doFinal() failed", e);
1314             }
1315         }
1316
1317         protected boolean engineVerify(byte[] sigBytes)
1318                 throws SignatureException {
1319             try {
1320                 byte[] out = cipher.doFinal(sigBytes);
1321                 byte[] dataBytes = data.toByteArray();
1322                 data.reset();
1323                 return MessageDigest.isEqual(out, dataBytes);
1324             } catch (BadPaddingException e) {
1325                 // e.g. wrong public key used
1326                 // return false rather than throwing exception
1327                 return false;
1328             } catch (IllegalBlockSizeException e) {
1329                 throw new SignatureException("doFinal() failed", e);
1330             }
1331         }
1332
1333         protected void engineSetParameter(String param, Object value)
1334                 throws InvalidParameterException {
1335             throw new InvalidParameterException("Parameters not supported");
1336         }
1337
1338         protected Object engineGetParameter(String param)
1339                 throws InvalidParameterException {
1340             throw new InvalidParameterException("Parameters not supported");
1341         }
1342
1343     }
1344
1345 }
1346
Powered by JavaMelody