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