1 /*
   2  * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package 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     void chooseFirstProvider() {
 442         // empty, overridden in Delegate
 443     }
 444 
 445     /**
 446      * Initializes this object for verification. If this method is called
 447      * again with a different argument, it negates the effect
 448      * of this call.
 449      *
 450      * @param publicKey the public key of the identity whose signature is
 451      * going to be verified.
 452      *
 453      * @exception InvalidKeyException if the key is invalid.
 454      */
 455     public final void initVerify(PublicKey publicKey)
 456             throws InvalidKeyException {
 457         engineInitVerify(publicKey);
 458         state = VERIFY;
 459 
 460         if (!skipDebug && pdebug != null) {
 461             pdebug.println("Signature." + algorithm +
 462                 " verification algorithm from: " + this.provider.getName());
 463         }
 464     }
 465 
 466     /**
 467      * Initializes this object for verification, using the public key from
 468      * the given certificate.
 469      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
 470      * extension field marked as critical, and the value of the <i>key usage</i>
 471      * extension field implies that the public key in
 472      * the certificate and its corresponding private key are not
 473      * supposed to be used for digital signatures, an
 474      * {@code InvalidKeyException} is thrown.
 475      *
 476      * @param certificate the certificate of the identity whose signature is
 477      * going to be verified.
 478      *
 479      * @exception InvalidKeyException  if the public key in the certificate
 480      * is not encoded properly or does not include required  parameter
 481      * information or cannot be used for digital signature purposes.
 482      * @since 1.3
 483      */
 484     public final void initVerify(Certificate certificate)
 485             throws InvalidKeyException {
 486         // If the certificate is of type X509Certificate,
 487         // we should check whether it has a Key Usage
 488         // extension marked as critical.
 489         if (certificate instanceof java.security.cert.X509Certificate) {
 490             // Check whether the cert has a key usage extension
 491             // marked as a critical extension.
 492             // The OID for KeyUsage extension is 2.5.29.15.
 493             X509Certificate cert = (X509Certificate)certificate;
 494             Set<String> critSet = cert.getCriticalExtensionOIDs();
 495 
 496             if (critSet != null && !critSet.isEmpty()
 497                 && critSet.contains("2.5.29.15")) {
 498                 boolean[] keyUsageInfo = cert.getKeyUsage();
 499                 // keyUsageInfo[0] is for digitalSignature.
 500                 if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
 501                     throw new InvalidKeyException("Wrong key usage");
 502             }
 503         }
 504 
 505         PublicKey publicKey = certificate.getPublicKey();
 506         engineInitVerify(publicKey);
 507         state = VERIFY;
 508 
 509         if (!skipDebug && pdebug != null) {
 510             pdebug.println("Signature." + algorithm +
 511                 " verification algorithm from: " + this.provider.getName());
 512         }
 513     }
 514 
 515     /**
 516      * Initialize this object for signing. If this method is called
 517      * again with a different argument, it negates the effect
 518      * of this call.
 519      *
 520      * @param privateKey the private key of the identity whose signature
 521      * is going to be generated.
 522      *
 523      * @exception InvalidKeyException if the key is invalid.
 524      */
 525     public final void initSign(PrivateKey privateKey)
 526             throws InvalidKeyException {
 527         engineInitSign(privateKey);
 528         state = SIGN;
 529 
 530         if (!skipDebug && pdebug != null) {
 531             pdebug.println("Signature." + algorithm +
 532                 " signing algorithm from: " + this.provider.getName());
 533         }
 534     }
 535 
 536     /**
 537      * Initialize this object for signing. If this method is called
 538      * again with a different argument, it negates the effect
 539      * of this call.
 540      *
 541      * @param privateKey the private key of the identity whose signature
 542      * is going to be generated.
 543      *
 544      * @param random the source of randomness for this signature.
 545      *
 546      * @exception InvalidKeyException if the key is invalid.
 547      */
 548     public final void initSign(PrivateKey privateKey, SecureRandom random)
 549             throws InvalidKeyException {
 550         engineInitSign(privateKey, random);
 551         state = SIGN;
 552 
 553         if (!skipDebug && pdebug != null) {
 554             pdebug.println("Signature." + algorithm +
 555                 " signing algorithm from: " + this.provider.getName());
 556         }
 557     }
 558 
 559     /**
 560      * Returns the signature bytes of all the data updated.
 561      * The format of the signature depends on the underlying
 562      * signature scheme.
 563      *
 564      * <p>A call to this method resets this signature object to the state
 565      * it was in when previously initialized for signing via a
 566      * call to {@code initSign(PrivateKey)}. That is, the object is
 567      * reset and available to generate another signature from the same
 568      * signer, if desired, via new calls to {@code update} and
 569      * {@code sign}.
 570      *
 571      * @return the signature bytes of the signing operation's result.
 572      *
 573      * @exception SignatureException if this signature object is not
 574      * initialized properly or if this signature algorithm is unable to
 575      * process the input data provided.
 576      */
 577     public final byte[] sign() throws SignatureException {
 578         if (state == SIGN) {
 579             return engineSign();
 580         }
 581         throw new SignatureException("object not initialized for " +
 582                                      "signing");
 583     }
 584 
 585     /**
 586      * Finishes the signature operation and stores the resulting signature
 587      * bytes in the provided buffer {@code outbuf}, starting at
 588      * {@code offset}.
 589      * The format of the signature depends on the underlying
 590      * signature scheme.
 591      *
 592      * <p>This signature object is reset to its initial state (the state it
 593      * was in after a call to one of the {@code initSign} methods) and
 594      * can be reused to generate further signatures with the same private key.
 595      *
 596      * @param outbuf buffer for the signature result.
 597      *
 598      * @param offset offset into {@code outbuf} where the signature is
 599      * stored.
 600      *
 601      * @param len number of bytes within {@code outbuf} allotted for the
 602      * signature.
 603      *
 604      * @return the number of bytes placed into {@code outbuf}.
 605      *
 606      * @exception SignatureException if this signature object is not
 607      *     initialized properly, if this signature algorithm is unable to
 608      *     process the input data provided, or if {@code len} is less
 609      *     than the actual signature length.
 610      * @exception IllegalArgumentException if {@code outbuf} is {@code null},
 611      *     or {@code offset} or {@code len} is less than 0, or the sum of
 612      *     {@code offset} and {@code len} is greater than the length of
 613      *     {@code outbuf}.
 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      * @exception IllegalArgumentException if {@code data} is {@code null},
 752      *     or {@code off} or {@code len} is less than 0, or the sum of
 753      *     {@code off} and {@code len} is greater than the length of
 754      *     {@code data}.
 755      */
 756     public final void update(byte[] data, int off, int len)
 757             throws SignatureException {
 758         if (state == SIGN || state == VERIFY) {
 759             if (data == null) {
 760                 throw new IllegalArgumentException("data is null");
 761             }
 762             if (off < 0 || len < 0) {
 763                 throw new IllegalArgumentException("off or len is less than 0");
 764             }
 765             if (data.length - off < len) {
 766                 throw new IllegalArgumentException
 767                     ("data too small for specified offset and length");
 768             }
 769             engineUpdate(data, off, len);
 770         } else {
 771             throw new SignatureException("object not initialized for "
 772                                          + "signature or verification");
 773         }
 774     }
 775 
 776     /**
 777      * Updates the data to be signed or verified using the specified
 778      * ByteBuffer. Processes the {@code data.remaining()} bytes
 779      * starting at {@code data.position()}.
 780      * Upon return, the buffer's position will be equal to its limit;
 781      * its limit will not have changed.
 782      *
 783      * @param data the ByteBuffer
 784      *
 785      * @exception SignatureException if this signature object is not
 786      * initialized properly.
 787      * @since 1.5
 788      */
 789     public final void update(ByteBuffer data) throws SignatureException {
 790         if ((state != SIGN) && (state != VERIFY)) {
 791             throw new SignatureException("object not initialized for "
 792                                          + "signature or verification");
 793         }
 794         if (data == null) {
 795             throw new NullPointerException();
 796         }
 797         engineUpdate(data);
 798     }
 799 
 800     /**
 801      * Returns the name of the algorithm for this signature object.
 802      *
 803      * @return the name of the algorithm for this signature object.
 804      */
 805     public final String getAlgorithm() {
 806         return this.algorithm;
 807     }
 808 
 809     /**
 810      * Returns a string representation of this signature object,
 811      * providing information that includes the state of the object
 812      * and the name of the algorithm used.
 813      *
 814      * @return a string representation of this signature object.
 815      */
 816     public String toString() {
 817         String initState = "";
 818         switch (state) {
 819         case UNINITIALIZED:
 820             initState = "<not initialized>";
 821             break;
 822         case VERIFY:
 823             initState = "<initialized for verifying>";
 824             break;
 825         case SIGN:
 826             initState = "<initialized for signing>";
 827             break;
 828         }
 829         return "Signature object: " + getAlgorithm() + initState;
 830     }
 831 
 832     /**
 833      * Sets the specified algorithm parameter to the specified value.
 834      * This method supplies a general-purpose mechanism through
 835      * which it is possible to set the various parameters of this object.
 836      * A parameter may be any settable parameter for the algorithm, such as
 837      * a parameter size, or a source of random bits for signature generation
 838      * (if appropriate), or an indication of whether or not to perform
 839      * a specific but optional computation. A uniform algorithm-specific
 840      * naming scheme for each parameter is desirable but left unspecified
 841      * at this time.
 842      *
 843      * @param param the string identifier of the parameter.
 844      * @param value the parameter value.
 845      *
 846      * @exception InvalidParameterException if {@code param} is an
 847      * invalid parameter for this signature algorithm engine,
 848      * the parameter is already set
 849      * and cannot be set again, a security exception occurs, and so on.
 850      *
 851      * @see #getParameter
 852      *
 853      * @deprecated Use
 854      * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
 855      * setParameter}.
 856      */
 857     @Deprecated
 858     public final void setParameter(String param, Object value)
 859             throws InvalidParameterException {
 860         engineSetParameter(param, value);
 861     }
 862 
 863     /**
 864      * Initializes this signature engine with the specified parameter set.
 865      *
 866      * @param params the parameters
 867      *
 868      * @exception InvalidAlgorithmParameterException if the given parameters
 869      * are inappropriate for this signature engine
 870      *
 871      * @see #getParameters
 872      */
 873     public final void setParameter(AlgorithmParameterSpec params)
 874             throws InvalidAlgorithmParameterException {
 875         engineSetParameter(params);
 876     }
 877 
 878     /**
 879      * Returns the parameters used with this signature object.
 880      *
 881      * <p>The returned parameters may be the same that were used to initialize
 882      * this signature, or may contain a combination of default and randomly
 883      * generated parameter values used by the underlying signature
 884      * implementation if this signature requires algorithm parameters but
 885      * was not initialized with any.
 886      *
 887      * @return the parameters used with this signature, or null if this
 888      * signature does not use any parameters.
 889      *
 890      * @see #setParameter(AlgorithmParameterSpec)
 891      * @since 1.4
 892      */
 893     public final AlgorithmParameters getParameters() {
 894         return engineGetParameters();
 895     }
 896 
 897     /**
 898      * Gets the value of the specified algorithm parameter. This method
 899      * supplies a general-purpose mechanism through which it is possible to
 900      * get the various parameters of this object. A parameter may be any
 901      * settable parameter for the algorithm, such as a parameter size, or
 902      * a source of random bits for signature generation (if appropriate),
 903      * or an indication of whether or not to perform a specific but optional
 904      * computation. A uniform algorithm-specific naming scheme for each
 905      * parameter is desirable but left unspecified at this time.
 906      *
 907      * @param param the string name of the parameter.
 908      *
 909      * @return the object that represents the parameter value, or null if
 910      * there is none.
 911      *
 912      * @exception InvalidParameterException if {@code param} is an invalid
 913      * parameter for this engine, or another exception occurs while
 914      * trying to get this parameter.
 915      *
 916      * @see #setParameter(String, Object)
 917      *
 918      * @deprecated
 919      */
 920     @Deprecated
 921     public final Object getParameter(String param)
 922             throws InvalidParameterException {
 923         return engineGetParameter(param);
 924     }
 925 
 926     /**
 927      * Returns a clone if the implementation is cloneable.
 928      *
 929      * @return a clone if the implementation is cloneable.
 930      *
 931      * @exception CloneNotSupportedException if this is called
 932      * on an implementation that does not support {@code Cloneable}.
 933      */
 934     public Object clone() throws CloneNotSupportedException {
 935         if (this instanceof Cloneable) {
 936             return super.clone();
 937         } else {
 938             throw new CloneNotSupportedException();
 939         }
 940     }
 941 
 942     /*
 943      * The following class allows providers to extend from SignatureSpi
 944      * rather than from Signature. It represents a Signature with an
 945      * encapsulated, provider-supplied SPI object (of type SignatureSpi).
 946      * If the provider implementation is an instance of SignatureSpi, the
 947      * getInstance() methods above return an instance of this class, with
 948      * the SPI object encapsulated.
 949      *
 950      * Note: All SPI methods from the original Signature class have been
 951      * moved up the hierarchy into a new class (SignatureSpi), which has
 952      * been interposed in the hierarchy between the API (Signature)
 953      * and its original parent (Object).
 954      */
 955 
 956     @SuppressWarnings("deprecation")
 957     private static class Delegate extends Signature {
 958 
 959         // The provider implementation (delegate)
 960         // filled in once the provider is selected
 961         private SignatureSpi sigSpi;
 962 
 963         // lock for mutex during provider selection
 964         private final Object lock;
 965 
 966         // next service to try in provider selection
 967         // null once provider is selected
 968         private Service firstService;
 969 
 970         // remaining services to try in provider selection
 971         // null once provider is selected
 972         private Iterator<Service> serviceIterator;
 973 
 974         // constructor
 975         Delegate(SignatureSpi sigSpi, String algorithm) {
 976             super(algorithm);
 977             this.sigSpi = sigSpi;
 978             this.lock = null; // no lock needed
 979         }
 980 
 981         // used with delayed provider selection
 982         Delegate(Service service,
 983                         Iterator<Service> iterator, String algorithm) {
 984             super(algorithm);
 985             this.firstService = service;
 986             this.serviceIterator = iterator;
 987             this.lock = new Object();
 988         }
 989 
 990         /**
 991          * Returns a clone if the delegate is cloneable.
 992          *
 993          * @return a clone if the delegate is cloneable.
 994          *
 995          * @exception CloneNotSupportedException if this is called on a
 996          * delegate that does not support {@code Cloneable}.
 997          */
 998         public Object clone() throws CloneNotSupportedException {
 999             chooseFirstProvider();
1000             if (sigSpi instanceof Cloneable) {
1001                 SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
1002                 // Because 'algorithm' and 'provider' are private
1003                 // members of our supertype, we must perform a cast to
1004                 // access them.
1005                 Signature that =
1006                     new Delegate(sigSpiClone, ((Signature)this).algorithm);
1007                 that.provider = ((Signature)this).provider;
1008                 return that;
1009             } else {
1010                 throw new CloneNotSupportedException();
1011             }
1012         }
1013 
1014         private static SignatureSpi newInstance(Service s)
1015                 throws NoSuchAlgorithmException {
1016             if (s.getType().equals("Cipher")) {
1017                 // must be NONEwithRSA
1018                 try {
1019                     Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
1020                     return new CipherAdapter(c);
1021                 } catch (NoSuchPaddingException e) {
1022                     throw new NoSuchAlgorithmException(e);
1023                 }
1024             } else {
1025                 Object o = s.newInstance(null);
1026                 if (o instanceof SignatureSpi == false) {
1027                     throw new NoSuchAlgorithmException
1028                         ("Not a SignatureSpi: " + o.getClass().getName());
1029                 }
1030                 return (SignatureSpi)o;
1031             }
1032         }
1033 
1034         // max number of debug warnings to print from chooseFirstProvider()
1035         private static int warnCount = 10;
1036 
1037         /**
1038          * Choose the Spi from the first provider available. Used if
1039          * delayed provider selection is not possible because initSign()/
1040          * initVerify() is not the first method called.
1041          */
1042         void chooseFirstProvider() {
1043             if (sigSpi != null) {
1044                 return;
1045             }
1046             synchronized (lock) {
1047                 if (sigSpi != null) {
1048                     return;
1049                 }
1050                 if (debug != null) {
1051                     int w = --warnCount;
1052                     if (w >= 0) {
1053                         debug.println("Signature.init() not first method "
1054                             + "called, disabling delayed provider selection");
1055                         if (w == 0) {
1056                             debug.println("Further warnings of this type will "
1057                                 + "be suppressed");
1058                         }
1059                         new Exception("Call trace").printStackTrace();
1060                     }
1061                 }
1062                 Exception lastException = null;
1063                 while ((firstService != null) || serviceIterator.hasNext()) {
1064                     Service s;
1065                     if (firstService != null) {
1066                         s = firstService;
1067                         firstService = null;
1068                     } else {
1069                         s = serviceIterator.next();
1070                     }
1071                     if (isSpi(s) == false) {
1072                         continue;
1073                     }
1074                     try {
1075                         sigSpi = newInstance(s);
1076                         provider = s.getProvider();
1077                         // not needed any more
1078                         firstService = null;
1079                         serviceIterator = null;
1080                         return;
1081                     } catch (NoSuchAlgorithmException e) {
1082                         lastException = e;
1083                     }
1084                 }
1085                 ProviderException e = new ProviderException
1086                         ("Could not construct SignatureSpi instance");
1087                 if (lastException != null) {
1088                     e.initCause(lastException);
1089                 }
1090                 throw e;
1091             }
1092         }
1093 
1094         private void chooseProvider(int type, Key key, SecureRandom random)
1095                 throws InvalidKeyException {
1096             synchronized (lock) {
1097                 if (sigSpi != null) {
1098                     init(sigSpi, type, key, random);
1099                     return;
1100                 }
1101                 Exception lastException = null;
1102                 while ((firstService != null) || serviceIterator.hasNext()) {
1103                     Service s;
1104                     if (firstService != null) {
1105                         s = firstService;
1106                         firstService = null;
1107                     } else {
1108                         s = serviceIterator.next();
1109                     }
1110                     // if provider says it does not support this key, ignore it
1111                     if (s.supportsParameter(key) == false) {
1112                         continue;
1113                     }
1114                     // if instance is not a SignatureSpi, ignore it
1115                     if (isSpi(s) == false) {
1116                         continue;
1117                     }
1118                     try {
1119                         SignatureSpi spi = newInstance(s);
1120                         init(spi, type, key, random);
1121                         provider = s.getProvider();
1122                         sigSpi = spi;
1123                         firstService = null;
1124                         serviceIterator = null;
1125                         return;
1126                     } catch (Exception e) {
1127                         // NoSuchAlgorithmException from newInstance()
1128                         // InvalidKeyException from init()
1129                         // RuntimeException (ProviderException) from init()
1130                         if (lastException == null) {
1131                             lastException = e;
1132                         }
1133                     }
1134                 }
1135                 // no working provider found, fail
1136                 if (lastException instanceof InvalidKeyException) {
1137                     throw (InvalidKeyException)lastException;
1138                 }
1139                 if (lastException instanceof RuntimeException) {
1140                     throw (RuntimeException)lastException;
1141                 }
1142                 String k = (key != null) ? key.getClass().getName() : "(null)";
1143                 throw new InvalidKeyException
1144                     ("No installed provider supports this key: "
1145                     + k, lastException);
1146             }
1147         }
1148 
1149         private final static int I_PUB     = 1;
1150         private final static int I_PRIV    = 2;
1151         private final static int I_PRIV_SR = 3;
1152 
1153         private void init(SignatureSpi spi, int type, Key  key,
1154                 SecureRandom random) throws InvalidKeyException {
1155             switch (type) {
1156             case I_PUB:
1157                 spi.engineInitVerify((PublicKey)key);
1158                 break;
1159             case I_PRIV:
1160                 spi.engineInitSign((PrivateKey)key);
1161                 break;
1162             case I_PRIV_SR:
1163                 spi.engineInitSign((PrivateKey)key, random);
1164                 break;
1165             default:
1166                 throw new AssertionError("Internal error: " + type);
1167             }
1168         }
1169 
1170         protected void engineInitVerify(PublicKey publicKey)
1171                 throws InvalidKeyException {
1172             if (sigSpi != null) {
1173                 sigSpi.engineInitVerify(publicKey);
1174             } else {
1175                 chooseProvider(I_PUB, publicKey, null);
1176             }
1177         }
1178 
1179         protected void engineInitSign(PrivateKey privateKey)
1180                 throws InvalidKeyException {
1181             if (sigSpi != null) {
1182                 sigSpi.engineInitSign(privateKey);
1183             } else {
1184                 chooseProvider(I_PRIV, privateKey, null);
1185             }
1186         }
1187 
1188         protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
1189                 throws InvalidKeyException {
1190             if (sigSpi != null) {
1191                 sigSpi.engineInitSign(privateKey, sr);
1192             } else {
1193                 chooseProvider(I_PRIV_SR, privateKey, sr);
1194             }
1195         }
1196 
1197         protected void engineUpdate(byte b) throws SignatureException {
1198             chooseFirstProvider();
1199             sigSpi.engineUpdate(b);
1200         }
1201 
1202         protected void engineUpdate(byte[] b, int off, int len)
1203                 throws SignatureException {
1204             chooseFirstProvider();
1205             sigSpi.engineUpdate(b, off, len);
1206         }
1207 
1208         protected void engineUpdate(ByteBuffer data) {
1209             chooseFirstProvider();
1210             sigSpi.engineUpdate(data);
1211         }
1212 
1213         protected byte[] engineSign() throws SignatureException {
1214             chooseFirstProvider();
1215             return sigSpi.engineSign();
1216         }
1217 
1218         protected int engineSign(byte[] outbuf, int offset, int len)
1219                 throws SignatureException {
1220             chooseFirstProvider();
1221             return sigSpi.engineSign(outbuf, offset, len);
1222         }
1223 
1224         protected boolean engineVerify(byte[] sigBytes)
1225                 throws SignatureException {
1226             chooseFirstProvider();
1227             return sigSpi.engineVerify(sigBytes);
1228         }
1229 
1230         protected boolean engineVerify(byte[] sigBytes, int offset, int length)
1231                 throws SignatureException {
1232             chooseFirstProvider();
1233             return sigSpi.engineVerify(sigBytes, offset, length);
1234         }
1235 
1236         protected void engineSetParameter(String param, Object value)
1237                 throws InvalidParameterException {
1238             chooseFirstProvider();
1239             sigSpi.engineSetParameter(param, value);
1240         }
1241 
1242         protected void engineSetParameter(AlgorithmParameterSpec params)
1243                 throws InvalidAlgorithmParameterException {
1244             chooseFirstProvider();
1245             sigSpi.engineSetParameter(params);
1246         }
1247 
1248         protected Object engineGetParameter(String param)
1249                 throws InvalidParameterException {
1250             chooseFirstProvider();
1251             return sigSpi.engineGetParameter(param);
1252         }
1253 
1254         protected AlgorithmParameters engineGetParameters() {
1255             chooseFirstProvider();
1256             return sigSpi.engineGetParameters();
1257         }
1258     }
1259 
1260     // adapter for RSA/ECB/PKCS1Padding ciphers
1261     @SuppressWarnings("deprecation")
1262     private static class CipherAdapter extends SignatureSpi {
1263 
1264         private final Cipher cipher;
1265 
1266         private ByteArrayOutputStream data;
1267 
1268         CipherAdapter(Cipher cipher) {
1269             this.cipher = cipher;
1270         }
1271 
1272         protected void engineInitVerify(PublicKey publicKey)
1273                 throws InvalidKeyException {
1274             cipher.init(Cipher.DECRYPT_MODE, publicKey);
1275             if (data == null) {
1276                 data = new ByteArrayOutputStream(128);
1277             } else {
1278                 data.reset();
1279             }
1280         }
1281 
1282         protected void engineInitSign(PrivateKey privateKey)
1283                 throws InvalidKeyException {
1284             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
1285             data = null;
1286         }
1287 
1288         protected void engineInitSign(PrivateKey privateKey,
1289                 SecureRandom random) throws InvalidKeyException {
1290             cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
1291             data = null;
1292         }
1293 
1294         protected void engineUpdate(byte b) throws SignatureException {
1295             engineUpdate(new byte[] {b}, 0, 1);
1296         }
1297 
1298         protected void engineUpdate(byte[] b, int off, int len)
1299                 throws SignatureException {
1300             if (data != null) {
1301                 data.write(b, off, len);
1302                 return;
1303             }
1304             byte[] out = cipher.update(b, off, len);
1305             if ((out != null) && (out.length != 0)) {
1306                 throw new SignatureException
1307                     ("Cipher unexpectedly returned data");
1308             }
1309         }
1310 
1311         protected byte[] engineSign() throws SignatureException {
1312             try {
1313                 return cipher.doFinal();
1314             } catch (IllegalBlockSizeException e) {
1315                 throw new SignatureException("doFinal() failed", e);
1316             } catch (BadPaddingException e) {
1317                 throw new SignatureException("doFinal() failed", e);
1318             }
1319         }
1320 
1321         protected boolean engineVerify(byte[] sigBytes)
1322                 throws SignatureException {
1323             try {
1324                 byte[] out = cipher.doFinal(sigBytes);
1325                 byte[] dataBytes = data.toByteArray();
1326                 data.reset();
1327                 return Arrays.equals(out, dataBytes);
1328             } catch (BadPaddingException e) {
1329                 // e.g. wrong public key used
1330                 // return false rather than throwing exception
1331                 return false;
1332             } catch (IllegalBlockSizeException e) {
1333                 throw new SignatureException("doFinal() failed", e);
1334             }
1335         }
1336 
1337         protected void engineSetParameter(String param, Object value)
1338                 throws InvalidParameterException {
1339             throw new InvalidParameterException("Parameters not supported");
1340         }
1341 
1342         protected Object engineGetParameter(String param)
1343                 throws InvalidParameterException {
1344             throw new InvalidParameterException("Parameters not supported");
1345         }
1346 
1347     }
1348 
1349 }