1/*
2 * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.security;
27
28import java.security.spec.AlgorithmParameterSpec;
29import java.util.*;
30import java.util.concurrent.ConcurrentHashMap;
31import java.io.*;
32import java.security.cert.Certificate;
33import java.security.cert.X509Certificate;
34
35import java.nio.ByteBuffer;
36
37import java.security.Provider.Service;
38
39import javax.crypto.Cipher;
40import javax.crypto.IllegalBlockSizeException;
41import javax.crypto.BadPaddingException;
42import javax.crypto.NoSuchPaddingException;
43
44import sun.security.util.Debug;
45import sun.security.jca.*;
46import sun.security.jca.GetInstance.Instance;
47
48/**
49 * The Signature class is used to provide applications the functionality
50 * of a digital signature algorithm. Digital signatures are used for
51 * authentication and integrity assurance of digital data.
52 *
53 * <p> The signature algorithm can be, among others, the NIST standard
54 * DSA, using DSA and SHA-256. The DSA algorithm using the
55 * SHA-256 message digest algorithm can be specified as {@code SHA256withDSA}.
56 * In the case of RSA the signing algorithm could be specified as, for example,
57 * {@code SHA256withRSA}.
58 * The algorithm name must be specified, as there is no default.
59 *
60 * <p> A Signature object can be used to generate and verify digital
61 * signatures.
62 *
63 * <p> There are three phases to the use of a Signature object for
64 * either signing data or verifying a signature:<ol>
65 *
66 * <li>Initialization, with either
67 *
68 *     <ul>
69 *
70 *     <li>a public key, which initializes the signature for
71 *     verification (see {@link #initVerify(PublicKey) initVerify}), or
72 *
73 *     <li>a private key (and optionally a Secure Random Number Generator),
74 *     which initializes the signature for signing
75 *     (see {@link #initSign(PrivateKey)}
76 *     and {@link #initSign(PrivateKey, SecureRandom)}).
77 *
78 *     </ul>
79 *
80 * <li>Updating
81 *
82 * <p>Depending on the type of initialization, this will update the
83 * bytes to be signed or verified. See the
84 * {@link #update(byte) update} methods.
85 *
86 * <li>Signing or Verifying a signature on all updated bytes. See the
87 * {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
88 * method.
89 *
90 * </ol>
91 *
92 * <p>Note that this class is abstract and extends from
93 * {@code SignatureSpi} for historical reasons.
94 * Application developers should only take notice of the methods defined in
95 * this {@code Signature} class; all the methods in
96 * the superclass are intended for cryptographic service providers who wish to
97 * supply their own implementations of digital signature algorithms.
98 *
99 * <p> Every implementation of the Java platform is required to support the
100 * following standard {@code Signature} algorithms:
101 * <ul>
102 * <li>{@code SHA1withDSA}</li>
103 * <li>{@code SHA256withDSA}</li>
104 * <li>{@code SHA1withRSA}</li>
105 * <li>{@code SHA256withRSA}</li>
106 * </ul>
107 * These algorithms are described in the <a href=
108 * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
109 * Signature section</a> of the
110 * Java Security Standard Algorithm Names Specification.
111 * Consult the release documentation for your implementation to see if any
112 * other algorithms are supported.
113 *
114 * @author Benjamin Renaud
115 * @since 1.1
116 *
117 */
118
119public 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 static final int UNINITIALIZED = 0;
144
145    /**
146     * Possible {@link #state} value, signifying that
147     * this signature object has been initialized for signing.
148     */
149    protected static final int SIGN = 2;
150
151    /**
152     * Possible {@link #state} value, signifying that
153     * this signature object has been initialized for verification.
154     */
155    protected static final 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}/../specs/security/standard-names.html#signature-algorithms">
168     * Java Security Standard Algorithm Names Specification</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 static final String RSA_SIGNATURE = "NONEwithRSA";
177
178    // name of the equivalent cipher alg
179    private static final String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
180
181    // all the services we need to lookup for compatibility with Cipher
182    private static final List<ServiceId> rsaIds = List.of(
183        new ServiceId("Signature", "NONEwithRSA"),
184        new ServiceId("Cipher", "RSA/ECB/PKCS1Padding"),
185        new ServiceId("Cipher", "RSA/ECB"),
186        new ServiceId("Cipher", "RSA//PKCS1Padding"),
187        new ServiceId("Cipher", "RSA"));
188
189    /**
190     * Returns a Signature object that implements the specified signature
191     * algorithm.
192     *
193     * <p> This method traverses the list of registered security Providers,
194     * starting with the most preferred Provider.
195     * A new Signature object encapsulating the
196     * SignatureSpi implementation from the first
197     * Provider that supports the specified algorithm is returned.
198     *
199     * <p> Note that the list of registered providers may be retrieved via
200     * the {@link Security#getProviders() Security.getProviders()} method.
201     *
202     * @implNote
203     * The JDK Reference Implementation additionally uses the
204     * {@code jdk.security.provider.preferred}
205     * {@link Security#getProperty(String) Security} property to determine
206     * the preferred provider order for the specified algorithm. This
207     * may be different than the order of providers returned by
208     * {@link Security#getProviders() Security.getProviders()}.
209     *
210     * @param algorithm the standard name of the algorithm requested.
211     * See the Signature section in the <a href=
212     * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
213     * Java Security Standard Algorithm Names Specification</a>
214     * for information about standard algorithm names.
215     *
216     * @return the new {@code Signature} object
217     *
218     * @throws NoSuchAlgorithmException if no {@code Provider} supports a
219     *         {@code Signature} implementation for the
220     *         specified algorithm
221     *
222     * @throws NullPointerException if {@code algorithm} is {@code null}
223     *
224     * @see Provider
225     */
226    public static Signature getInstance(String algorithm)
227            throws NoSuchAlgorithmException {
228        Objects.requireNonNull(algorithm, "null algorithm name");
229        List<Service> list;
230        if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
231            list = GetInstance.getServices(rsaIds);
232        } else {
233            list = GetInstance.getServices("Signature", algorithm);
234        }
235        Iterator<Service> t = list.iterator();
236        if (t.hasNext() == false) {
237            throw new NoSuchAlgorithmException
238                (algorithm + " Signature not available");
239        }
240        // try services until we find an Spi or a working Signature subclass
241        NoSuchAlgorithmException failure;
242        do {
243            Service s = t.next();
244            if (isSpi(s)) {
245                return new Delegate(s, t, algorithm);
246            } else {
247                // must be a subclass of Signature, disable dynamic selection
248                try {
249                    Instance instance =
250                        GetInstance.getInstance(s, SignatureSpi.class);
251                    return getInstance(instance, algorithm);
252                } catch (NoSuchAlgorithmException e) {
253                    failure = e;
254                }
255            }
256        } while (t.hasNext());
257        throw failure;
258    }
259
260    private static Signature getInstance(Instance instance, String algorithm) {
261        Signature sig;
262        if (instance.impl instanceof Signature) {
263            sig = (Signature)instance.impl;
264            sig.algorithm = algorithm;
265        } else {
266            SignatureSpi spi = (SignatureSpi)instance.impl;
267            sig = new Delegate(spi, algorithm);
268        }
269        sig.provider = instance.provider;
270        return sig;
271    }
272
273    private static final Map<String,Boolean> signatureInfo;
274
275    static {
276        signatureInfo = new ConcurrentHashMap<>();
277        Boolean TRUE = Boolean.TRUE;
278        // pre-initialize with values for our SignatureSpi implementations
279        signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
280        signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
281        signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
282        signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
283        signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
284        signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
285        signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
286        signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
287        signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
288        signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
289    }
290
291    private static boolean isSpi(Service s) {
292        if (s.getType().equals("Cipher")) {
293            // must be a CipherSpi, which we can wrap with the CipherAdapter
294            return true;
295        }
296        String className = s.getClassName();
297        Boolean result = signatureInfo.get(className);
298        if (result == null) {
299            try {
300                Object instance = s.newInstance(null);
301                // Signature extends SignatureSpi
302                // so it is a "real" Spi if it is an
303                // instance of SignatureSpi but not Signature
304                boolean r = (instance instanceof SignatureSpi)
305                                && (instance instanceof Signature == false);
306                if ((debug != null) && (r == false)) {
307                    debug.println("Not a SignatureSpi " + className);
308                    debug.println("Delayed provider selection may not be "
309                        + "available for algorithm " + s.getAlgorithm());
310                }
311                result = Boolean.valueOf(r);
312                signatureInfo.put(className, result);
313            } catch (Exception e) {
314                // something is wrong, assume not an SPI
315                return false;
316            }
317        }
318        return result.booleanValue();
319    }
320
321    /**
322     * Returns a Signature object that implements the specified signature
323     * algorithm.
324     *
325     * <p> A new Signature object encapsulating the
326     * SignatureSpi implementation from the specified provider
327     * is returned.  The specified provider must be registered
328     * in the security provider list.
329     *
330     * <p> Note that the list of registered providers may be retrieved via
331     * the {@link Security#getProviders() Security.getProviders()} method.
332     *
333     * @param algorithm the name of the algorithm requested.
334     * See the Signature section in the <a href=
335     * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
336     * Java Security Standard Algorithm Names Specification</a>
337     * for information about standard algorithm names.
338     *
339     * @param provider the name of the provider.
340     *
341     * @return the new {@code Signature} object
342     *
343     * @throws IllegalArgumentException if the provider name is {@code null}
344     *         or empty
345     *
346     * @throws NoSuchAlgorithmException if a {@code SignatureSpi}
347     *         implementation for the specified algorithm is not
348     *         available from the specified provider
349     *
350     * @throws NoSuchProviderException if the specified provider is not
351     *         registered in the security provider list
352     *
353     * @throws NullPointerException if {@code algorithm} is {@code null}
354     *
355     * @see Provider
356     */
357    public static Signature getInstance(String algorithm, String provider)
358            throws NoSuchAlgorithmException, NoSuchProviderException {
359        Objects.requireNonNull(algorithm, "null algorithm name");
360        if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
361            // exception compatibility with existing code
362            if ((provider == null) || (provider.length() == 0)) {
363                throw new IllegalArgumentException("missing provider");
364            }
365            Provider p = Security.getProvider(provider);
366            if (p == null) {
367                throw new NoSuchProviderException
368                    ("no such provider: " + provider);
369            }
370            return getInstanceRSA(p);
371        }
372        Instance instance = GetInstance.getInstance
373                ("Signature", SignatureSpi.class, algorithm, provider);
374        return getInstance(instance, algorithm);
375    }
376
377    /**
378     * Returns a Signature object that implements the specified
379     * signature algorithm.
380     *
381     * <p> A new Signature object encapsulating the
382     * SignatureSpi implementation from the specified Provider
383     * object is returned.  Note that the specified Provider object
384     * does not have to be registered in the provider list.
385     *
386     * @param algorithm the name of the algorithm requested.
387     * See the Signature section in the <a href=
388     * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
389     * Java Security Standard Algorithm Names Specification</a>
390     * for information about standard algorithm names.
391     *
392     * @param provider the provider.
393     *
394     * @return the new {@code Signature} object
395     *
396     * @throws IllegalArgumentException if the provider is {@code null}
397     *
398     * @throws NoSuchAlgorithmException if a {@code SignatureSpi}
399     *         implementation for the specified algorithm is not available
400     *         from the specified {@code Provider} object
401     *
402     * @throws NullPointerException if {@code algorithm} is {@code null}
403     *
404     * @see Provider
405     *
406     * @since 1.4
407     */
408    public static Signature getInstance(String algorithm, Provider provider)
409            throws NoSuchAlgorithmException {
410        Objects.requireNonNull(algorithm, "null algorithm name");
411        if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
412            // exception compatibility with existing code
413            if (provider == null) {
414                throw new IllegalArgumentException("missing provider");
415            }
416            return getInstanceRSA(provider);
417        }
418        Instance instance = GetInstance.getInstance
419                ("Signature", SignatureSpi.class, algorithm, provider);
420        return getInstance(instance, algorithm);
421    }
422
423    // return an implementation for NONEwithRSA, which is a special case
424    // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
425    private static Signature getInstanceRSA(Provider p)
426            throws NoSuchAlgorithmException {
427        // try Signature first
428        Service s = p.getService("Signature", RSA_SIGNATURE);
429        if (s != null) {
430            Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
431            return getInstance(instance, RSA_SIGNATURE);
432        }
433        // check Cipher
434        try {
435            Cipher c = Cipher.getInstance(RSA_CIPHER, p);
436            return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
437        } catch (GeneralSecurityException e) {
438            // throw Signature style exception message to avoid confusion,
439            // but append Cipher exception as cause
440            throw new NoSuchAlgorithmException("no such algorithm: "
441                + RSA_SIGNATURE + " for provider " + p.getName(), e);
442        }
443    }
444
445    /**
446     * Returns the provider of this signature object.
447     *
448     * @return the provider of this signature object
449     */
450    public final Provider getProvider() {
451        chooseFirstProvider();
452        return this.provider;
453    }
454
455    private String getProviderName() {
456        return (provider == null)  ? "(no provider)" : provider.getName();
457    }
458
459    void chooseFirstProvider() {
460        // empty, overridden in Delegate
461    }
462
463    /**
464     * Initializes this object for verification. If this method is called
465     * again with a different argument, it negates the effect
466     * of this call.
467     *
468     * @param publicKey the public key of the identity whose signature is
469     * going to be verified.
470     *
471     * @exception InvalidKeyException if the key is invalid.
472     */
473    public final void initVerify(PublicKey publicKey)
474            throws InvalidKeyException {
475        engineInitVerify(publicKey);
476        state = VERIFY;
477
478        if (!skipDebug && pdebug != null) {
479            pdebug.println("Signature." + algorithm +
480                " verification algorithm from: " + getProviderName());
481        }
482    }
483
484    /**
485     * Initializes this object for verification, using the public key from
486     * the given certificate.
487     * <p>If the certificate is of type X.509 and has a <i>key usage</i>
488     * extension field marked as critical, and the value of the <i>key usage</i>
489     * extension field implies that the public key in
490     * the certificate and its corresponding private key are not
491     * supposed to be used for digital signatures, an
492     * {@code InvalidKeyException} is thrown.
493     *
494     * @param certificate the certificate of the identity whose signature is
495     * going to be verified.
496     *
497     * @exception InvalidKeyException  if the public key in the certificate
498     * is not encoded properly or does not include required  parameter
499     * information or cannot be used for digital signature purposes.
500     * @since 1.3
501     */
502    public final void initVerify(Certificate certificate)
503            throws InvalidKeyException {
504        // If the certificate is of type X509Certificate,
505        // we should check whether it has a Key Usage
506        // extension marked as critical.
507        if (certificate instanceof java.security.cert.X509Certificate) {
508            // Check whether the cert has a key usage extension
509            // marked as a critical extension.
510            // The OID for KeyUsage extension is 2.5.29.15.
511            X509Certificate cert = (X509Certificate)certificate;
512            Set<String> critSet = cert.getCriticalExtensionOIDs();
513
514            if (critSet != null && !critSet.isEmpty()
515                && critSet.contains("2.5.29.15")) {
516                boolean[] keyUsageInfo = cert.getKeyUsage();
517                // keyUsageInfo[0] is for digitalSignature.
518                if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
519                    throw new InvalidKeyException("Wrong key usage");
520            }
521        }
522
523        PublicKey publicKey = certificate.getPublicKey();
524        engineInitVerify(publicKey);
525        state = VERIFY;
526
527        if (!skipDebug && pdebug != null) {
528            pdebug.println("Signature." + algorithm +
529                " verification algorithm from: " + getProviderName());
530        }
531    }
532
533    /**
534     * Initialize this object for signing. If this method is called
535     * again with a different argument, it negates the effect
536     * of this call.
537     *
538     * @param privateKey the private key of the identity whose signature
539     * is going to be generated.
540     *
541     * @exception InvalidKeyException if the key is invalid.
542     */
543    public final void initSign(PrivateKey privateKey)
544            throws InvalidKeyException {
545        engineInitSign(privateKey);
546        state = SIGN;
547
548        if (!skipDebug && pdebug != null) {
549            pdebug.println("Signature." + algorithm +
550                " signing algorithm from: " + getProviderName());
551        }
552    }
553
554    /**
555     * Initialize this object for signing. If this method is called
556     * again with a different argument, it negates the effect
557     * of this call.
558     *
559     * @param privateKey the private key of the identity whose signature
560     * is going to be generated.
561     *
562     * @param random the source of randomness for this signature.
563     *
564     * @exception InvalidKeyException if the key is invalid.
565     */
566    public final void initSign(PrivateKey privateKey, SecureRandom random)
567            throws InvalidKeyException {
568        engineInitSign(privateKey, random);
569        state = SIGN;
570
571        if (!skipDebug && pdebug != null) {
572            pdebug.println("Signature." + algorithm +
573                " signing algorithm from: " + getProviderName());
574        }
575    }
576
577    /**
578     * Returns the signature bytes of all the data updated.
579     * The format of the signature depends on the underlying
580     * signature scheme.
581     *
582     * <p>A call to this method resets this signature object to the state
583     * it was in when previously initialized for signing via a
584     * call to {@code initSign(PrivateKey)}. That is, the object is
585     * reset and available to generate another signature from the same
586     * signer, if desired, via new calls to {@code update} and
587     * {@code sign}.
588     *
589     * @return the signature bytes of the signing operation's result.
590     *
591     * @exception SignatureException if this signature object is not
592     * initialized properly or if this signature algorithm is unable to
593     * process the input data provided.
594     */
595    public final byte[] sign() throws SignatureException {
596        if (state == SIGN) {
597            return engineSign();
598        }
599        throw new SignatureException("object not initialized for " +
600                                     "signing");
601    }
602
603    /**
604     * Finishes the signature operation and stores the resulting signature
605     * bytes in the provided buffer {@code outbuf}, starting at
606     * {@code offset}.
607     * The format of the signature depends on the underlying
608     * signature scheme.
609     *
610     * <p>This signature object is reset to its initial state (the state it
611     * was in after a call to one of the {@code initSign} methods) and
612     * can be reused to generate further signatures with the same private key.
613     *
614     * @param outbuf buffer for the signature result.
615     *
616     * @param offset offset into {@code outbuf} where the signature is
617     * stored.
618     *
619     * @param len number of bytes within {@code outbuf} allotted for the
620     * signature.
621     *
622     * @return the number of bytes placed into {@code outbuf}.
623     *
624     * @exception SignatureException if this signature object is not
625     *     initialized properly, if this signature algorithm is unable to
626     *     process the input data provided, or if {@code len} is less
627     *     than the actual signature length.
628     * @exception IllegalArgumentException if {@code outbuf} is {@code null},
629     *     or {@code offset} or {@code len} is less than 0, or the sum of
630     *     {@code offset} and {@code len} is greater than the length of
631     *     {@code outbuf}.
632     *
633     * @since 1.2
634     */
635    public final int sign(byte[] outbuf, int offset, int len)
636        throws SignatureException {
637        if (outbuf == null) {
638            throw new IllegalArgumentException("No output buffer given");
639        }
640        if (offset < 0 || len < 0) {
641            throw new IllegalArgumentException("offset or len is less than 0");
642        }
643        if (outbuf.length - offset < len) {
644            throw new IllegalArgumentException
645                ("Output buffer too small for specified offset and length");
646        }
647        if (state != SIGN) {
648            throw new SignatureException("object not initialized for " +
649                                         "signing");
650        }
651        return engineSign(outbuf, offset, len);
652    }
653
654    /**
655     * Verifies the passed-in signature.
656     *
657     * <p>A call to this method resets this signature object to the state
658     * it was in when previously initialized for verification via a
659     * call to {@code initVerify(PublicKey)}. That is, the object is
660     * reset and available to verify another signature from the identity
661     * whose public key was specified in the call to {@code initVerify}.
662     *
663     * @param signature the signature bytes to be verified.
664     *
665     * @return true if the signature was verified, false if not.
666     *
667     * @exception SignatureException if this signature object is not
668     * initialized properly, the passed-in signature is improperly
669     * encoded or of the wrong type, if this signature algorithm is unable to
670     * process the input data provided, etc.
671     */
672    public final boolean verify(byte[] signature) throws SignatureException {
673        if (state == VERIFY) {
674            return engineVerify(signature);
675        }
676        throw new SignatureException("object not initialized for " +
677                                     "verification");
678    }
679
680    /**
681     * Verifies the passed-in signature in the specified array
682     * of bytes, starting at the specified offset.
683     *
684     * <p>A call to this method resets this signature object to the state
685     * it was in when previously initialized for verification via a
686     * call to {@code initVerify(PublicKey)}. That is, the object is
687     * reset and available to verify another signature from the identity
688     * whose public key was specified in the call to {@code initVerify}.
689     *
690     *
691     * @param signature the signature bytes to be verified.
692     * @param offset the offset to start from in the array of bytes.
693     * @param length the number of bytes to use, starting at offset.
694     *
695     * @return true if the signature was verified, false if not.
696     *
697     * @exception SignatureException if this signature object is not
698     * initialized properly, the passed-in signature is improperly
699     * encoded or of the wrong type, if this signature algorithm is unable to
700     * process the input data provided, etc.
701     * @exception IllegalArgumentException if the {@code signature}
702     * byte array is null, or the {@code offset} or {@code length}
703     * is less than 0, or the sum of the {@code offset} and
704     * {@code length} is greater than the length of the
705     * {@code signature} byte array.
706     * @since 1.4
707     */
708    public final boolean verify(byte[] signature, int offset, int length)
709        throws SignatureException {
710        if (state == VERIFY) {
711            if (signature == null) {
712                throw new IllegalArgumentException("signature is null");
713            }
714            if (offset < 0 || length < 0) {
715                throw new IllegalArgumentException
716                    ("offset or length is less than 0");
717            }
718            if (signature.length - offset < length) {
719                throw new IllegalArgumentException
720                    ("signature too small for specified offset and length");
721            }
722
723            return engineVerify(signature, offset, length);
724        }
725        throw new SignatureException("object not initialized for " +
726                                     "verification");
727    }
728
729    /**
730     * Updates the data to be signed or verified by a byte.
731     *
732     * @param b the byte 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 b) throws SignatureException {
738        if (state == VERIFY || state == SIGN) {
739            engineUpdate(b);
740        } else {
741            throw new SignatureException("object not initialized for "
742                                         + "signature or verification");
743        }
744    }
745
746    /**
747     * Updates the data to be signed or verified, using the specified
748     * array of bytes.
749     *
750     * @param data the byte array to use for the update.
751     *
752     * @exception SignatureException if this signature object is not
753     * initialized properly.
754     */
755    public final void update(byte[] data) throws SignatureException {
756        update(data, 0, data.length);
757    }
758
759    /**
760     * Updates the data to be signed or verified, using the specified
761     * array of bytes, starting at the specified offset.
762     *
763     * @param data the array of bytes.
764     * @param off the offset to start from in the array of bytes.
765     * @param len the number of bytes to use, starting at offset.
766     *
767     * @exception SignatureException if this signature object is not
768     *     initialized properly.
769     * @exception IllegalArgumentException if {@code data} is {@code null},
770     *     or {@code off} or {@code len} is less than 0, or the sum of
771     *     {@code off} and {@code len} is greater than the length of
772     *     {@code data}.
773     */
774    public final void update(byte[] data, int off, int len)
775            throws SignatureException {
776        if (state == SIGN || state == VERIFY) {
777            if (data == null) {
778                throw new IllegalArgumentException("data is null");
779            }
780            if (off < 0 || len < 0) {
781                throw new IllegalArgumentException("off or len is less than 0");
782            }
783            if (data.length - off < len) {
784                throw new IllegalArgumentException
785                    ("data too small for specified offset and length");
786            }
787            engineUpdate(data, off, len);
788        } else {
789            throw new SignatureException("object not initialized for "
790                                         + "signature or verification");
791        }
792    }
793
794    /**
795     * Updates the data to be signed or verified using the specified
796     * ByteBuffer. Processes the {@code data.remaining()} bytes
797     * starting at {@code data.position()}.
798     * Upon return, the buffer's position will be equal to its limit;
799     * its limit will not have changed.
800     *
801     * @param data the ByteBuffer
802     *
803     * @exception SignatureException if this signature object is not
804     * initialized properly.
805     * @since 1.5
806     */
807    public final void update(ByteBuffer data) throws SignatureException {
808        if ((state != SIGN) && (state != VERIFY)) {
809            throw new SignatureException("object not initialized for "
810                                         + "signature or verification");
811        }
812        if (data == null) {
813            throw new NullPointerException();
814        }
815        engineUpdate(data);
816    }
817
818    /**
819     * Returns the name of the algorithm for this signature object.
820     *
821     * @return the name of the algorithm for this signature object.
822     */
823    public final String getAlgorithm() {
824        return this.algorithm;
825    }
826
827    /**
828     * Returns a string representation of this signature object,
829     * providing information that includes the state of the object
830     * and the name of the algorithm used.
831     *
832     * @return a string representation of this signature object.
833     */
834    public String toString() {
835        String initState = "";
836        switch (state) {
837        case UNINITIALIZED:
838            initState = "<not initialized>";
839            break;
840        case VERIFY:
841            initState = "<initialized for verifying>";
842            break;
843        case SIGN:
844            initState = "<initialized for signing>";
845            break;
846        }
847        return "Signature object: " + getAlgorithm() + initState;
848    }
849
850    /**
851     * Sets the specified algorithm parameter to the specified value.
852     * This method supplies a general-purpose mechanism through
853     * which it is possible to set the various parameters of this object.
854     * A parameter may be any settable parameter for the algorithm, such as
855     * a parameter size, or a source of random bits for signature generation
856     * (if appropriate), or an indication of whether or not to perform
857     * a specific but optional computation. A uniform algorithm-specific
858     * naming scheme for each parameter is desirable but left unspecified
859     * at this time.
860     *
861     * @param param the string identifier of the parameter.
862     * @param value the parameter value.
863     *
864     * @exception InvalidParameterException if {@code param} is an
865     * invalid parameter for this signature algorithm engine,
866     * the parameter is already set
867     * and cannot be set again, a security exception occurs, and so on.
868     *
869     * @see #getParameter
870     *
871     * @deprecated Use
872     * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
873     * setParameter}.
874     */
875    @Deprecated
876    public final void setParameter(String param, Object value)
877            throws InvalidParameterException {
878        engineSetParameter(param, value);
879    }
880
881    /**
882     * Initializes this signature engine with the specified parameter set.
883     *
884     * @param params the parameters
885     *
886     * @exception InvalidAlgorithmParameterException if the given parameters
887     * are inappropriate for this signature engine
888     *
889     * @see #getParameters
890     */
891    public final void setParameter(AlgorithmParameterSpec params)
892            throws InvalidAlgorithmParameterException {
893        engineSetParameter(params);
894    }
895
896    /**
897     * Returns the parameters used with this signature object.
898     *
899     * <p>The returned parameters may be the same that were used to initialize
900     * this signature, or may contain a combination of default and randomly
901     * generated parameter values used by the underlying signature
902     * implementation if this signature requires algorithm parameters but
903     * was not initialized with any.
904     *
905     * @return the parameters used with this signature, or null if this
906     * signature does not use any parameters.
907     *
908     * @see #setParameter(AlgorithmParameterSpec)
909     * @since 1.4
910     */
911    public final AlgorithmParameters getParameters() {
912        return engineGetParameters();
913    }
914
915    /**
916     * Gets the value of the specified algorithm parameter. This method
917     * supplies a general-purpose mechanism through which it is possible to
918     * get the various parameters of this object. A parameter may be any
919     * settable parameter for the algorithm, such as a parameter size, or
920     * a source of random bits for signature generation (if appropriate),
921     * or an indication of whether or not to perform a specific but optional
922     * computation. A uniform algorithm-specific naming scheme for each
923     * parameter is desirable but left unspecified at this time.
924     *
925     * @param param the string name of the parameter.
926     *
927     * @return the object that represents the parameter value, or null if
928     * there is none.
929     *
930     * @exception InvalidParameterException if {@code param} is an invalid
931     * parameter for this engine, or another exception occurs while
932     * trying to get this parameter.
933     *
934     * @see #setParameter(String, Object)
935     *
936     * @deprecated
937     */
938    @Deprecated
939    public final Object getParameter(String param)
940            throws InvalidParameterException {
941        return engineGetParameter(param);
942    }
943
944    /**
945     * Returns a clone if the implementation is cloneable.
946     *
947     * @return a clone if the implementation is cloneable.
948     *
949     * @exception CloneNotSupportedException if this is called
950     * on an implementation that does not support {@code Cloneable}.
951     */
952    public Object clone() throws CloneNotSupportedException {
953        if (this instanceof Cloneable) {
954            return super.clone();
955        } else {
956            throw new CloneNotSupportedException();
957        }
958    }
959
960    /*
961     * The following class allows providers to extend from SignatureSpi
962     * rather than from Signature. It represents a Signature with an
963     * encapsulated, provider-supplied SPI object (of type SignatureSpi).
964     * If the provider implementation is an instance of SignatureSpi, the
965     * getInstance() methods above return an instance of this class, with
966     * the SPI object encapsulated.
967     *
968     * Note: All SPI methods from the original Signature class have been
969     * moved up the hierarchy into a new class (SignatureSpi), which has
970     * been interposed in the hierarchy between the API (Signature)
971     * and its original parent (Object).
972     */
973
974    @SuppressWarnings("deprecation")
975    private static class Delegate extends Signature {
976
977        // The provider implementation (delegate)
978        // filled in once the provider is selected
979        private SignatureSpi sigSpi;
980
981        // lock for mutex during provider selection
982        private final Object lock;
983
984        // next service to try in provider selection
985        // null once provider is selected
986        private Service firstService;
987
988        // remaining services to try in provider selection
989        // null once provider is selected
990        private Iterator<Service> serviceIterator;
991
992        // constructor
993        Delegate(SignatureSpi sigSpi, String algorithm) {
994            super(algorithm);
995            this.sigSpi = sigSpi;
996            this.lock = null; // no lock needed
997        }
998
999        // used with delayed provider selection
1000        Delegate(Service service,
1001                        Iterator<Service> iterator, String algorithm) {
1002            super(algorithm);
1003            this.firstService = service;
1004            this.serviceIterator = iterator;
1005            this.lock = new Object();
1006        }
1007
1008        /**
1009         * Returns a clone if the delegate is cloneable.
1010         *
1011         * @return a clone if the delegate is cloneable.
1012         *
1013         * @exception CloneNotSupportedException if this is called on a
1014         * delegate that does not support {@code Cloneable}.
1015         */
1016        public Object clone() throws CloneNotSupportedException {
1017            chooseFirstProvider();
1018            if (sigSpi instanceof Cloneable) {
1019                SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
1020                // Because 'algorithm' and 'provider' are private
1021                // members of our supertype, we must perform a cast to
1022                // access them.
1023                Signature that =
1024                    new Delegate(sigSpiClone, ((Signature)this).algorithm);
1025                that.provider = ((Signature)this).provider;
1026                return that;
1027            } else {
1028                throw new CloneNotSupportedException();
1029            }
1030        }
1031
1032        private static SignatureSpi newInstance(Service s)
1033                throws NoSuchAlgorithmException {
1034            if (s.getType().equals("Cipher")) {
1035                // must be NONEwithRSA
1036                try {
1037                    Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
1038                    return new CipherAdapter(c);
1039                } catch (NoSuchPaddingException e) {
1040                    throw new NoSuchAlgorithmException(e);
1041                }
1042            } else {
1043                Object o = s.newInstance(null);
1044                if (o instanceof SignatureSpi == false) {
1045                    throw new NoSuchAlgorithmException
1046                        ("Not a SignatureSpi: " + o.getClass().getName());
1047                }
1048                return (SignatureSpi)o;
1049            }
1050        }
1051
1052        // max number of debug warnings to print from chooseFirstProvider()
1053        private static int warnCount = 10;
1054
1055        /**
1056         * Choose the Spi from the first provider available. Used if
1057         * delayed provider selection is not possible because initSign()/
1058         * initVerify() is not the first method called.
1059         */
1060        void chooseFirstProvider() {
1061            if (sigSpi != null) {
1062                return;
1063            }
1064            synchronized (lock) {
1065                if (sigSpi != null) {
1066                    return;
1067                }
1068                if (debug != null) {
1069                    int w = --warnCount;
1070                    if (w >= 0) {
1071                        debug.println("Signature.init() not first method "
1072                            + "called, disabling delayed provider selection");
1073                        if (w == 0) {
1074                            debug.println("Further warnings of this type will "
1075                                + "be suppressed");
1076                        }
1077                        new Exception("Call trace").printStackTrace();
1078                    }
1079                }
1080                Exception lastException = null;
1081                while ((firstService != null) || serviceIterator.hasNext()) {
1082                    Service s;
1083                    if (firstService != null) {
1084                        s = firstService;
1085                        firstService = null;
1086                    } else {
1087                        s = serviceIterator.next();
1088                    }
1089                    if (isSpi(s) == false) {
1090                        continue;
1091                    }
1092                    try {
1093                        sigSpi = newInstance(s);
1094                        provider = s.getProvider();
1095                        // not needed any more
1096                        firstService = null;
1097                        serviceIterator = null;
1098                        return;
1099                    } catch (NoSuchAlgorithmException e) {
1100                        lastException = e;
1101                    }
1102                }
1103                ProviderException e = new ProviderException
1104                        ("Could not construct SignatureSpi instance");
1105                if (lastException != null) {
1106                    e.initCause(lastException);
1107                }
1108                throw e;
1109            }
1110        }
1111
1112        private void chooseProvider(int type, Key key, SecureRandom random)
1113                throws InvalidKeyException {
1114            synchronized (lock) {
1115                if (sigSpi != null) {
1116                    init(sigSpi, type, key, random);
1117                    return;
1118                }
1119                Exception lastException = null;
1120                while ((firstService != null) || serviceIterator.hasNext()) {
1121                    Service s;
1122                    if (firstService != null) {
1123                        s = firstService;
1124                        firstService = null;
1125                    } else {
1126                        s = serviceIterator.next();
1127                    }
1128                    // if provider says it does not support this key, ignore it
1129                    if (s.supportsParameter(key) == false) {
1130                        continue;
1131                    }
1132                    // if instance is not a SignatureSpi, ignore it
1133                    if (isSpi(s) == false) {
1134                        continue;
1135                    }
1136                    try {
1137                        SignatureSpi spi = newInstance(s);
1138                        init(spi, type, key, random);
1139                        provider = s.getProvider();
1140                        sigSpi = spi;
1141                        firstService = null;
1142                        serviceIterator = null;
1143                        return;
1144                    } catch (Exception e) {
1145                        // NoSuchAlgorithmException from newInstance()
1146                        // InvalidKeyException from init()
1147                        // RuntimeException (ProviderException) from init()
1148                        if (lastException == null) {
1149                            lastException = e;
1150                        }
1151                    }
1152                }
1153                // no working provider found, fail
1154                if (lastException instanceof InvalidKeyException) {
1155                    throw (InvalidKeyException)lastException;
1156                }
1157                if (lastException instanceof RuntimeException) {
1158                    throw (RuntimeException)lastException;
1159                }
1160                String k = (key != null) ? key.getClass().getName() : "(null)";
1161                throw new InvalidKeyException
1162                    ("No installed provider supports this key: "
1163                    + k, lastException);
1164            }
1165        }
1166
1167        private static final int I_PUB     = 1;
1168        private static final int I_PRIV    = 2;
1169        private static final int I_PRIV_SR = 3;
1170
1171        private void init(SignatureSpi spi, int type, Key  key,
1172                SecureRandom random) throws InvalidKeyException {
1173            switch (type) {
1174            case I_PUB:
1175                spi.engineInitVerify((PublicKey)key);
1176                break;
1177            case I_PRIV:
1178                spi.engineInitSign((PrivateKey)key);
1179                break;
1180            case I_PRIV_SR:
1181                spi.engineInitSign((PrivateKey)key, random);
1182                break;
1183            default:
1184                throw new AssertionError("Internal error: " + type);
1185            }
1186        }
1187
1188        protected void engineInitVerify(PublicKey publicKey)
1189                throws InvalidKeyException {
1190            if (sigSpi != null) {
1191                sigSpi.engineInitVerify(publicKey);
1192            } else {
1193                chooseProvider(I_PUB, publicKey, null);
1194            }
1195        }
1196
1197        protected void engineInitSign(PrivateKey privateKey)
1198                throws InvalidKeyException {
1199            if (sigSpi != null) {
1200                sigSpi.engineInitSign(privateKey);
1201            } else {
1202                chooseProvider(I_PRIV, privateKey, null);
1203            }
1204        }
1205
1206        protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
1207                throws InvalidKeyException {
1208            if (sigSpi != null) {
1209                sigSpi.engineInitSign(privateKey, sr);
1210            } else {
1211                chooseProvider(I_PRIV_SR, privateKey, sr);
1212            }
1213        }
1214
1215        protected void engineUpdate(byte b) throws SignatureException {
1216            chooseFirstProvider();
1217            sigSpi.engineUpdate(b);
1218        }
1219
1220        protected void engineUpdate(byte[] b, int off, int len)
1221                throws SignatureException {
1222            chooseFirstProvider();
1223            sigSpi.engineUpdate(b, off, len);
1224        }
1225
1226        protected void engineUpdate(ByteBuffer data) {
1227            chooseFirstProvider();
1228            sigSpi.engineUpdate(data);
1229        }
1230
1231        protected byte[] engineSign() throws SignatureException {
1232            chooseFirstProvider();
1233            return sigSpi.engineSign();
1234        }
1235
1236        protected int engineSign(byte[] outbuf, int offset, int len)
1237                throws SignatureException {
1238            chooseFirstProvider();
1239            return sigSpi.engineSign(outbuf, offset, len);
1240        }
1241
1242        protected boolean engineVerify(byte[] sigBytes)
1243                throws SignatureException {
1244            chooseFirstProvider();
1245            return sigSpi.engineVerify(sigBytes);
1246        }
1247
1248        protected boolean engineVerify(byte[] sigBytes, int offset, int length)
1249                throws SignatureException {
1250            chooseFirstProvider();
1251            return sigSpi.engineVerify(sigBytes, offset, length);
1252        }
1253
1254        protected void engineSetParameter(String param, Object value)
1255                throws InvalidParameterException {
1256            chooseFirstProvider();
1257            sigSpi.engineSetParameter(param, value);
1258        }
1259
1260        protected void engineSetParameter(AlgorithmParameterSpec params)
1261                throws InvalidAlgorithmParameterException {
1262            chooseFirstProvider();
1263            sigSpi.engineSetParameter(params);
1264        }
1265
1266        protected Object engineGetParameter(String param)
1267                throws InvalidParameterException {
1268            chooseFirstProvider();
1269            return sigSpi.engineGetParameter(param);
1270        }
1271
1272        protected AlgorithmParameters engineGetParameters() {
1273            chooseFirstProvider();
1274            return sigSpi.engineGetParameters();
1275        }
1276    }
1277
1278    // adapter for RSA/ECB/PKCS1Padding ciphers
1279    @SuppressWarnings("deprecation")
1280    private static class CipherAdapter extends SignatureSpi {
1281
1282        private final Cipher cipher;
1283
1284        private ByteArrayOutputStream data;
1285
1286        CipherAdapter(Cipher cipher) {
1287            this.cipher = cipher;
1288        }
1289
1290        protected void engineInitVerify(PublicKey publicKey)
1291                throws InvalidKeyException {
1292            cipher.init(Cipher.DECRYPT_MODE, publicKey);
1293            if (data == null) {
1294                data = new ByteArrayOutputStream(128);
1295            } else {
1296                data.reset();
1297            }
1298        }
1299
1300        protected void engineInitSign(PrivateKey privateKey)
1301                throws InvalidKeyException {
1302            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
1303            data = null;
1304        }
1305
1306        protected void engineInitSign(PrivateKey privateKey,
1307                SecureRandom random) throws InvalidKeyException {
1308            cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
1309            data = null;
1310        }
1311
1312        protected void engineUpdate(byte b) throws SignatureException {
1313            engineUpdate(new byte[] {b}, 0, 1);
1314        }
1315
1316        protected void engineUpdate(byte[] b, int off, int len)
1317                throws SignatureException {
1318            if (data != null) {
1319                data.write(b, off, len);
1320                return;
1321            }
1322            byte[] out = cipher.update(b, off, len);
1323            if ((out != null) && (out.length != 0)) {
1324                throw new SignatureException
1325                    ("Cipher unexpectedly returned data");
1326            }
1327        }
1328
1329        protected byte[] engineSign() throws SignatureException {
1330            try {
1331                return cipher.doFinal();
1332            } catch (IllegalBlockSizeException e) {
1333                throw new SignatureException("doFinal() failed", e);
1334            } catch (BadPaddingException e) {
1335                throw new SignatureException("doFinal() failed", e);
1336            }
1337        }
1338
1339        protected boolean engineVerify(byte[] sigBytes)
1340                throws SignatureException {
1341            try {
1342                byte[] out = cipher.doFinal(sigBytes);
1343                byte[] dataBytes = data.toByteArray();
1344                data.reset();
1345                return MessageDigest.isEqual(out, dataBytes);
1346            } catch (BadPaddingException e) {
1347                // e.g. wrong public key used
1348                // return false rather than throwing exception
1349                return false;
1350            } catch (IllegalBlockSizeException e) {
1351                throw new SignatureException("doFinal() failed", e);
1352            }
1353        }
1354
1355        protected void engineSetParameter(String param, Object value)
1356                throws InvalidParameterException {
1357            throw new InvalidParameterException("Parameters not supported");
1358        }
1359
1360        protected Object engineGetParameter(String param)
1361                throws InvalidParameterException {
1362            throw new InvalidParameterException("Parameters not supported");
1363        }
1364
1365    }
1366
1367}
1368