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