1 /*
   2  * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  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-1. The DSA algorithm using the
  55  * SHA-1 message digest algorithm can be specified as {@code SHA1withDSA}.
  56  * In the case of RSA, there are multiple choices for the message digest
  57  * algorithm, so the signing algorithm could be specified as, for example,
  58  * {@code MD2withRSA}, {@code MD5withRSA}, or {@code SHA1withRSA}.
  59  * The algorithm name must be specified, as there is no default.
  60  *
  61  * <p> A Signature object can be used to generate and verify digital
  62  * signatures.
  63  *
  64  * <p> There are three phases to the use of a Signature object for
  65  * either signing data or verifying a signature:<ol>
  66  *
  67  * <li>Initialization, with either
  68  *
  69  *     <ul>
  70  *
  71  *     <li>a public key, which initializes the signature for
  72  *     verification (see {@link #initVerify(PublicKey) initVerify}), or
  73  *
  74  *     <li>a private key (and optionally a Secure Random Number Generator),
  75  *     which initializes the signature for signing
  76  *     (see {@link #initSign(PrivateKey)}
  77  *     and {@link #initSign(PrivateKey, SecureRandom)}).
  78  *
  79  *     </ul>
  80  *
  81  * <li>Updating
  82  *
  83  * <p>Depending on the type of initialization, this will update the
  84  * bytes to be signed or verified. See the
  85  * {@link #update(byte) update} methods.
  86  *
  87  * <li>Signing or Verifying a signature on all updated bytes. See the
  88  * {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
  89  * method.
  90  *
  91  * </ol>
  92  *
  93  * <p>Note that this class is abstract and extends from
  94  * {@code SignatureSpi} for historical reasons.
  95  * Application developers should only take notice of the methods defined in
  96  * this {@code Signature} class; all the methods in
  97  * the superclass are intended for cryptographic service providers who wish to
  98  * supply their own implementations of digital signature algorithms.
  99  *
 100  * <p> Every implementation of the Java platform is required to support the
 101  * following standard {@code Signature} algorithms:
 102  * <ul>
 103  * <li>{@code SHA1withDSA}</li>
 104  * <li>{@code SHA256withDSA}</li>
 105  * <li>{@code SHA1withRSA}</li>
 106  * <li>{@code SHA256withRSA}</li>
 107  * </ul>
 108  * These algorithms are described in the <a href=
 109  * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
 110  * Signature section</a> of the
 111  * Java Security Standard Algorithm Names Specification.
 112  * Consult the release documentation for your implementation to see if any
 113  * other algorithms are supported.
 114  *
 115  * @author Benjamin Renaud
 116  * @since 1.1
 117  *
 118  */
 119 
 120 public abstract class Signature extends SignatureSpi {
 121 
 122     private static final Debug debug =
 123                         Debug.getInstance("jca", "Signature");
 124 
 125     private static final Debug pdebug =
 126                         Debug.getInstance("provider", "Provider");
 127     private static final boolean skipDebug =
 128         Debug.isOn("engine=") && !Debug.isOn("signature");
 129 
 130     /*
 131      * The algorithm for this signature object.
 132      * This value is used to map an OID to the particular algorithm.
 133      * The mapping is done in AlgorithmObject.algOID(String algorithm)
 134      */
 135     private String algorithm;
 136 
 137     // The provider
 138     Provider provider;
 139 
 140     /**
 141      * Possible {@link #state} value, signifying that
 142      * this signature object has not yet been initialized.
 143      */
 144     protected static final int UNINITIALIZED = 0;
 145 
 146     /**
 147      * Possible {@link #state} value, signifying that
 148      * this signature object has been initialized for signing.
 149      */
 150     protected static final int SIGN = 2;
 151 
 152     /**
 153      * Possible {@link #state} value, signifying that
 154      * this signature object has been initialized for verification.
 155      */
 156     protected static final int VERIFY = 3;
 157 
 158     /**
 159      * Current state of this signature object.
 160      */
 161     protected int state = UNINITIALIZED;
 162 
 163     /**
 164      * Creates a Signature object for the specified algorithm.
 165      *
 166      * @param algorithm the standard string name of the algorithm.
 167      * See the Signature section in the <a href=
 168      * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
 169      * Java Security Standard Algorithm Names Specification</a>
 170      * for information about standard algorithm names.
 171      */
 172     protected Signature(String algorithm) {
 173         this.algorithm = algorithm;
 174     }
 175 
 176     // name of the special signature alg
 177     private static final String RSA_SIGNATURE = "NONEwithRSA";
 178 
 179     // name of the equivalent cipher alg
 180     private static final String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
 181 
 182     // all the services we need to lookup for compatibility with Cipher
 183     private static final List<ServiceId> rsaIds = List.of(
 184         new ServiceId("Signature", "NONEwithRSA"),
 185         new ServiceId("Cipher", "RSA/ECB/PKCS1Padding"),
 186         new ServiceId("Cipher", "RSA/ECB"),
 187         new ServiceId("Cipher", "RSA//PKCS1Padding"),
 188         new ServiceId("Cipher", "RSA"));
 189 
 190     /**
 191      * Returns a Signature object that implements the specified signature
 192      * algorithm.
 193      *
 194      * <p> This method traverses the list of registered security Providers,
 195      * starting with the most preferred Provider.
 196      * A new Signature object encapsulating the
 197      * SignatureSpi implementation from the first
 198      * Provider that supports the specified algorithm is returned.
 199      *
 200      * <p> Note that the list of registered providers may be retrieved via
 201      * the {@link Security#getProviders() Security.getProviders()} method.
 202      *
 203      * @implNote
 204      * The JDK Reference Implementation additionally uses the
 205      * {@code jdk.security.provider.preferred}
 206      * {@link Security#getProperty(String) Security} property to determine
 207      * the preferred provider order for the specified algorithm. This
 208      * may be different than the order of providers returned by
 209      * {@link Security#getProviders() Security.getProviders()}.
 210      *
 211      * @param algorithm the standard name of the algorithm requested.
 212      * See the Signature section in the <a href=
 213      * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
 214      * Java Security Standard Algorithm Names Specification</a>
 215      * for information about standard algorithm names.
 216      *
 217      * @return the new {@code Signature} object
 218      *
 219      * @throws NoSuchAlgorithmException if no {@code Provider} supports a
 220      *         {@code Signature} implementation for the
 221      *         specified algorithm
 222      *
 223      * @throws NullPointerException if {@code algorithm} is {@code null}
 224      *
 225      * @see Provider
 226      */
 227     public static Signature getInstance(String algorithm)
 228             throws NoSuchAlgorithmException {
 229         Objects.requireNonNull(algorithm, "null algorithm name");
 230         List<Service> list;
 231         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
 232             list = GetInstance.getServices(rsaIds);
 233         } else {
 234             list = GetInstance.getServices("Signature", algorithm);
 235         }
 236         Iterator<Service> t = list.iterator();
 237         if (t.hasNext() == false) {
 238             throw new NoSuchAlgorithmException
 239                 (algorithm + " Signature not available");
 240         }
 241         // try services until we find an Spi or a working Signature subclass
 242         NoSuchAlgorithmException failure;
 243         do {
 244             Service s = t.next();
 245             if (isSpi(s)) {
 246                 return new Delegate(s, t, algorithm);
 247             } else {
 248                 // must be a subclass of Signature, disable dynamic selection
 249                 try {
 250                     Instance instance =
 251                         GetInstance.getInstance(s, SignatureSpi.class);
 252                     return getInstance(instance, algorithm);
 253                 } catch (NoSuchAlgorithmException e) {
 254                     failure = e;
 255                 }
 256             }
 257         } while (t.hasNext());
 258         throw failure;
 259     }
 260 
 261     private static Signature getInstance(Instance instance, String algorithm) {
 262         Signature sig;
 263         if (instance.impl instanceof Signature) {
 264             sig = (Signature)instance.impl;
 265             sig.algorithm = algorithm;
 266         } else {
 267             SignatureSpi spi = (SignatureSpi)instance.impl;
 268             sig = new Delegate(spi, algorithm);
 269         }
 270         sig.provider = instance.provider;
 271         return sig;
 272     }
 273 
 274     private static final Map<String,Boolean> signatureInfo;
 275 
 276     static {
 277         signatureInfo = new ConcurrentHashMap<>();
 278         Boolean TRUE = Boolean.TRUE;
 279         // pre-initialize with values for our SignatureSpi implementations
 280         signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
 281         signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
 282         signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
 283         signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
 284         signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
 285         signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
 286         signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
 287         signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
 288         signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
 289         signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
 290     }
 291 
 292     private static boolean isSpi(Service s) {
 293         if (s.getType().equals("Cipher")) {
 294             // must be a CipherSpi, which we can wrap with the CipherAdapter
 295             return true;
 296         }
 297         String className = s.getClassName();
 298         Boolean result = signatureInfo.get(className);
 299         if (result == null) {
 300             try {
 301                 Object instance = s.newInstance(null);
 302                 // Signature extends SignatureSpi
 303                 // so it is a "real" Spi if it is an
 304                 // instance of SignatureSpi but not Signature
 305                 boolean r = (instance instanceof SignatureSpi)
 306                                 && (instance instanceof Signature == false);
 307                 if ((debug != null) && (r == false)) {
 308                     debug.println("Not a SignatureSpi " + className);
 309                     debug.println("Delayed provider selection may not be "
 310                         + "available for algorithm " + s.getAlgorithm());
 311                 }
 312                 result = Boolean.valueOf(r);
 313                 signatureInfo.put(className, result);
 314             } catch (Exception e) {
 315                 // something is wrong, assume not an SPI
 316                 return false;
 317             }
 318         }
 319         return result.booleanValue();
 320     }
 321 
 322     /**
 323      * Returns a Signature object that implements the specified signature
 324      * algorithm.
 325      *
 326      * <p> A new Signature object encapsulating the
 327      * SignatureSpi implementation from the specified provider
 328      * is returned.  The specified provider must be registered
 329      * in the security provider list.
 330      *
 331      * <p> Note that the list of registered providers may be retrieved via
 332      * the {@link Security#getProviders() Security.getProviders()} method.
 333      *
 334      * @param algorithm the name of the algorithm requested.
 335      * See the Signature section in the <a href=
 336      * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
 337      * Java Security Standard Algorithm Names Specification</a>
 338      * for information about standard algorithm names.
 339      *
 340      * @param provider the name of the provider.
 341      *
 342      * @return the new {@code Signature} object
 343      *
 344      * @throws IllegalArgumentException if the provider name is {@code null}
 345      *         or empty
 346      *
 347      * @throws NoSuchAlgorithmException if a {@code SignatureSpi}
 348      *         implementation for the specified algorithm is not
 349      *         available from the specified provider
 350      *
 351      * @throws NoSuchProviderException if the specified provider is not
 352      *         registered in the security provider list
 353      *
 354      * @throws NullPointerException if {@code algorithm} is {@code null}
 355      *
 356      * @see Provider
 357      */
 358     public static Signature getInstance(String algorithm, String provider)
 359             throws NoSuchAlgorithmException, NoSuchProviderException {
 360         Objects.requireNonNull(algorithm, "null algorithm name");
 361         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
 362             // exception compatibility with existing code
 363             if ((provider == null) || (provider.length() == 0)) {
 364                 throw new IllegalArgumentException("missing provider");
 365             }
 366             Provider p = Security.getProvider(provider);
 367             if (p == null) {
 368                 throw new NoSuchProviderException
 369                     ("no such provider: " + provider);
 370             }
 371             return getInstanceRSA(p);
 372         }
 373         Instance instance = GetInstance.getInstance
 374                 ("Signature", SignatureSpi.class, algorithm, provider);
 375         return getInstance(instance, algorithm);
 376     }
 377 
 378     /**
 379      * Returns a Signature object that implements the specified
 380      * signature algorithm.
 381      *
 382      * <p> A new Signature object encapsulating the
 383      * SignatureSpi implementation from the specified Provider
 384      * object is returned.  Note that the specified Provider object
 385      * does not have to be registered in the provider list.
 386      *
 387      * @param algorithm the name of the algorithm requested.
 388      * See the Signature section in the <a href=
 389      * "{@docRoot}/../specs/security/standard-names.html#signature-algorithms">
 390      * Java Security Standard Algorithm Names Specification</a>
 391      * for information about standard algorithm names.
 392      *
 393      * @param provider the provider.
 394      *
 395      * @return the new {@code Signature} object
 396      *
 397      * @throws IllegalArgumentException if the provider is {@code null}
 398      *
 399      * @throws NoSuchAlgorithmException if a {@code SignatureSpi}
 400      *         implementation for the specified algorithm is not available
 401      *         from the specified {@code Provider} object
 402      *
 403      * @throws NullPointerException if {@code algorithm} is {@code null}
 404      *
 405      * @see Provider
 406      *
 407      * @since 1.4
 408      */
 409     public static Signature getInstance(String algorithm, Provider provider)
 410             throws NoSuchAlgorithmException {
 411         Objects.requireNonNull(algorithm, "null algorithm name");
 412         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
 413             // exception compatibility with existing code
 414             if (provider == null) {
 415                 throw new IllegalArgumentException("missing provider");
 416             }
 417             return getInstanceRSA(provider);
 418         }
 419         Instance instance = GetInstance.getInstance
 420                 ("Signature", SignatureSpi.class, algorithm, provider);
 421         return getInstance(instance, algorithm);
 422     }
 423 
 424     // return an implementation for NONEwithRSA, which is a special case
 425     // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
 426     private static Signature getInstanceRSA(Provider p)
 427             throws NoSuchAlgorithmException {
 428         // try Signature first
 429         Service s = p.getService("Signature", RSA_SIGNATURE);
 430         if (s != null) {
 431             Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
 432             return getInstance(instance, RSA_SIGNATURE);
 433         }
 434         // check Cipher
 435         try {
 436             Cipher c = Cipher.getInstance(RSA_CIPHER, p);
 437             return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
 438         } catch (GeneralSecurityException e) {
 439             // throw Signature style exception message to avoid confusion,
 440             // but append Cipher exception as cause
 441             throw new NoSuchAlgorithmException("no such algorithm: "
 442                 + RSA_SIGNATURE + " for provider " + p.getName(), e);
 443         }
 444     }
 445 
 446     /**
 447      * Returns the provider of this signature object.
 448      *
 449      * @return the provider of this signature object
 450      */
 451     public final Provider getProvider() {
 452         chooseFirstProvider();
 453         return this.provider;
 454     }
 455 
 456     private String getProviderName() {
 457         return (provider == null)  ? "(no provider)" : provider.getName();
 458     }
 459 
 460     void chooseFirstProvider() {
 461         // empty, overridden in Delegate
 462     }
 463 
 464     /**
 465      * Initializes this object for verification. If this method is called
 466      * again with a different argument, it negates the effect
 467      * of this call.
 468      *
 469      * @param publicKey the public key of the identity whose signature is
 470      * going to be verified.
 471      *
 472      * @exception InvalidKeyException if the key is invalid.
 473      */
 474     public final void initVerify(PublicKey publicKey)
 475             throws InvalidKeyException {
 476         engineInitVerify(publicKey);
 477         state = VERIFY;
 478 
 479         if (!skipDebug && pdebug != null) {
 480             pdebug.println("Signature." + algorithm +
 481                 " verification algorithm from: " + getProviderName());
 482         }
 483     }
 484 
 485     /**
 486      * Initializes this object for verification, using the public key from
 487      * the given certificate.
 488      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
 489      * extension field marked as critical, and the value of the <i>key usage</i>
 490      * extension field implies that the public key in
 491      * the certificate and its corresponding private key are not
 492      * supposed to be used for digital signatures, an
 493      * {@code InvalidKeyException} is thrown.
 494      *
 495      * @param certificate the certificate of the identity whose signature is
 496      * going to be verified.
 497      *
 498      * @exception InvalidKeyException  if the public key in the certificate
 499      * is not encoded properly or does not include required  parameter
 500      * information or cannot be used for digital signature purposes.
 501      * @since 1.3
 502      */
 503     public final void initVerify(Certificate certificate)
 504             throws InvalidKeyException {
 505         // If the certificate is of type X509Certificate,
 506         // we should check whether it has a Key Usage
 507         // extension marked as critical.
 508         if (certificate instanceof java.security.cert.X509Certificate) {
 509             // Check whether the cert has a key usage extension
 510             // marked as a critical extension.
 511             // The OID for KeyUsage extension is 2.5.29.15.
 512             X509Certificate cert = (X509Certificate)certificate;
 513             Set<String> critSet = cert.getCriticalExtensionOIDs();
 514 
 515             if (critSet != null && !critSet.isEmpty()
 516                 && critSet.contains("2.5.29.15")) {
 517                 boolean[] keyUsageInfo = cert.getKeyUsage();
 518                 // keyUsageInfo[0] is for digitalSignature.
 519                 if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
 520                     throw new InvalidKeyException("Wrong key usage");
 521             }
 522         }
 523 
 524         PublicKey publicKey = certificate.getPublicKey();
 525         engineInitVerify(publicKey);
 526         state = VERIFY;
 527 
 528         if (!skipDebug && pdebug != null) {
 529             pdebug.println("Signature." + algorithm +
 530                 " verification algorithm from: " + getProviderName());
 531         }
 532     }
 533 
 534     /**
 535      * Initialize this object for signing. If this method is called
 536      * again with a different argument, it negates the effect
 537      * of this call.
 538      *
 539      * @param privateKey the private key of the identity whose signature
 540      * is going to be generated.
 541      *
 542      * @exception InvalidKeyException if the key is invalid.
 543      */
 544     public final void initSign(PrivateKey privateKey)
 545             throws InvalidKeyException {
 546         engineInitSign(privateKey);
 547         state = SIGN;
 548 
 549         if (!skipDebug && pdebug != null) {
 550             pdebug.println("Signature." + algorithm +
 551                 " signing algorithm from: " + getProviderName());
 552         }
 553     }
 554 
 555     /**
 556      * Initialize this object for signing. If this method is called
 557      * again with a different argument, it negates the effect
 558      * of this call.
 559      *
 560      * @param privateKey the private key of the identity whose signature
 561      * is going to be generated.
 562      *
 563      * @param random the source of randomness for this signature.
 564      *
 565      * @exception InvalidKeyException if the key is invalid.
 566      */
 567     public final void initSign(PrivateKey privateKey, SecureRandom random)
 568             throws InvalidKeyException {
 569         engineInitSign(privateKey, random);
 570         state = SIGN;
 571 
 572         if (!skipDebug && pdebug != null) {
 573             pdebug.println("Signature." + algorithm +
 574                 " signing algorithm from: " + getProviderName());
 575         }
 576     }
 577 
 578     /**
 579      * Returns the signature bytes of all the data updated.
 580      * The format of the signature depends on the underlying
 581      * signature scheme.
 582      *
 583      * <p>A call to this method resets this signature object to the state
 584      * it was in when previously initialized for signing via a
 585      * call to {@code initSign(PrivateKey)}. That is, the object is
 586      * reset and available to generate another signature from the same
 587      * signer, if desired, via new calls to {@code update} and
 588      * {@code sign}.
 589      *
 590      * @return the signature bytes of the signing operation's result.
 591      *
 592      * @exception SignatureException if this signature object is not
 593      * initialized properly or if this signature algorithm is unable to
 594      * process the input data provided.
 595      */
 596     public final byte[] sign() throws SignatureException {
 597         if (state == SIGN) {
 598             return engineSign();
 599         }
 600         throw new SignatureException("object not initialized for " +
 601                                      "signing");
 602     }
 603 
 604     /**
 605      * Finishes the signature operation and stores the resulting signature
 606      * bytes in the provided buffer {@code outbuf}, starting at
 607      * {@code offset}.
 608      * The format of the signature depends on the underlying
 609      * signature scheme.
 610      *
 611      * <p>This signature object is reset to its initial state (the state it
 612      * was in after a call to one of the {@code initSign} methods) and
 613      * can be reused to generate further signatures with the same private key.
 614      *
 615      * @param outbuf buffer for the signature result.
 616      *
 617      * @param offset offset into {@code outbuf} where the signature is
 618      * stored.
 619      *
 620      * @param len number of bytes within {@code outbuf} allotted for the
 621      * signature.
 622      *
 623      * @return the number of bytes placed into {@code outbuf}.
 624      *
 625      * @exception SignatureException if this signature object is not
 626      *     initialized properly, if this signature algorithm is unable to
 627      *     process the input data provided, or if {@code len} is less
 628      *     than the actual signature length.
 629      * @exception IllegalArgumentException if {@code outbuf} is {@code null},
 630      *     or {@code offset} or {@code len} is less than 0, or the sum of
 631      *     {@code offset} and {@code len} is greater than the length of
 632      *     {@code outbuf}.
 633      *
 634      * @since 1.2
 635      */
 636     public final int sign(byte[] outbuf, int offset, int len)
 637         throws SignatureException {
 638         if (outbuf == null) {
 639             throw new IllegalArgumentException("No output buffer given");
 640         }
 641         if (offset < 0 || len < 0) {
 642             throw new IllegalArgumentException("offset or len is less than 0");
 643         }
 644         if (outbuf.length - offset < len) {
 645             throw new IllegalArgumentException
 646                 ("Output buffer too small for specified offset and length");
 647         }
 648         if (state != SIGN) {
 649             throw new SignatureException("object not initialized for " +
 650                                          "signing");
 651         }
 652         return engineSign(outbuf, offset, len);
 653     }
 654 
 655     /**
 656      * Verifies the passed-in signature.
 657      *
 658      * <p>A call to this method resets this signature object to the state
 659      * it was in when previously initialized for verification via a
 660      * call to {@code initVerify(PublicKey)}. That is, the object is
 661      * reset and available to verify another signature from the identity
 662      * whose public key was specified in the call to {@code initVerify}.
 663      *
 664      * @param signature the signature bytes to be verified.
 665      *
 666      * @return true if the signature was verified, false if not.
 667      *
 668      * @exception SignatureException if this signature object is not
 669      * initialized properly, the passed-in signature is improperly
 670      * encoded or of the wrong type, if this signature algorithm is unable to
 671      * process the input data provided, etc.
 672      */
 673     public final boolean verify(byte[] signature) throws SignatureException {
 674         if (state == VERIFY) {
 675             return engineVerify(signature);
 676         }
 677         throw new SignatureException("object not initialized for " +
 678                                      "verification");
 679     }
 680 
 681     /**
 682      * Verifies the passed-in signature in the specified array
 683      * of bytes, starting at the specified offset.
 684      *
 685      * <p>A call to this method resets this signature object to the state
 686      * it was in when previously initialized for verification via a
 687      * call to {@code initVerify(PublicKey)}. That is, the object is
 688      * reset and available to verify another signature from the identity
 689      * whose public key was specified in the call to {@code initVerify}.
 690      *
 691      *
 692      * @param signature the signature bytes to be verified.
 693      * @param offset the offset to start from in the array of bytes.
 694      * @param length the number of bytes to use, starting at offset.
 695      *
 696      * @return true if the signature was verified, false if not.
 697      *
 698      * @exception SignatureException if this signature object is not
 699      * initialized properly, the passed-in signature is improperly
 700      * encoded or of the wrong type, if this signature algorithm is unable to
 701      * process the input data provided, etc.
 702      * @exception IllegalArgumentException if the {@code signature}
 703      * byte array is null, or the {@code offset} or {@code length}
 704      * is less than 0, or the sum of the {@code offset} and
 705      * {@code length} is greater than the length of the
 706      * {@code signature} byte array.
 707      * @since 1.4
 708      */
 709     public final boolean verify(byte[] signature, int offset, int length)
 710         throws SignatureException {
 711         if (state == VERIFY) {
 712             if (signature == null) {
 713                 throw new IllegalArgumentException("signature is null");
 714             }
 715             if (offset < 0 || length < 0) {
 716                 throw new IllegalArgumentException
 717                     ("offset or length is less than 0");
 718             }
 719             if (signature.length - offset < length) {
 720                 throw new IllegalArgumentException
 721                     ("signature too small for specified offset and length");
 722             }
 723 
 724             return engineVerify(signature, offset, length);
 725         }
 726         throw new SignatureException("object not initialized for " +
 727                                      "verification");
 728     }
 729 
 730     /**
 731      * Updates the data to be signed or verified by a byte.
 732      *
 733      * @param b the byte to use for the update.
 734      *
 735      * @exception SignatureException if this signature object is not
 736      * initialized properly.
 737      */
 738     public final void update(byte b) throws SignatureException {
 739         if (state == VERIFY || state == SIGN) {
 740             engineUpdate(b);
 741         } else {
 742             throw new SignatureException("object not initialized for "
 743                                          + "signature or verification");
 744         }
 745     }
 746 
 747     /**
 748      * Updates the data to be signed or verified, using the specified
 749      * array of bytes.
 750      *
 751      * @param data the byte array to use for the update.
 752      *
 753      * @exception SignatureException if this signature object is not
 754      * initialized properly.
 755      */
 756     public final void update(byte[] data) throws SignatureException {
 757         update(data, 0, data.length);
 758     }
 759 
 760     /**
 761      * Updates the data to be signed or verified, using the specified
 762      * array of bytes, starting at the specified offset.
 763      *
 764      * @param data the array of bytes.
 765      * @param off the offset to start from in the array of bytes.
 766      * @param len the number of bytes to use, starting at offset.
 767      *
 768      * @exception SignatureException if this signature object is not
 769      *     initialized properly.
 770      * @exception IllegalArgumentException if {@code data} is {@code null},
 771      *     or {@code off} or {@code len} is less than 0, or the sum of
 772      *     {@code off} and {@code len} is greater than the length of
 773      *     {@code data}.
 774      */
 775     public final void update(byte[] data, int off, int len)
 776             throws SignatureException {
 777         if (state == SIGN || state == VERIFY) {
 778             if (data == null) {
 779                 throw new IllegalArgumentException("data is null");
 780             }
 781             if (off < 0 || len < 0) {
 782                 throw new IllegalArgumentException("off or len is less than 0");
 783             }
 784             if (data.length - off < len) {
 785                 throw new IllegalArgumentException
 786                     ("data too small for specified offset and length");
 787             }
 788             engineUpdate(data, off, len);
 789         } else {
 790             throw new SignatureException("object not initialized for "
 791                                          + "signature or verification");
 792         }
 793     }
 794 
 795     /**
 796      * Updates the data to be signed or verified using the specified
 797      * ByteBuffer. Processes the {@code data.remaining()} bytes
 798      * starting at {@code data.position()}.
 799      * Upon return, the buffer's position will be equal to its limit;
 800      * its limit will not have changed.
 801      *
 802      * @param data the ByteBuffer
 803      *
 804      * @exception SignatureException if this signature object is not
 805      * initialized properly.
 806      * @since 1.5
 807      */
 808     public final void update(ByteBuffer data) throws SignatureException {
 809         if ((state != SIGN) && (state != VERIFY)) {
 810             throw new SignatureException("object not initialized for "
 811                                          + "signature or verification");
 812         }
 813         if (data == null) {
 814             throw new NullPointerException();
 815         }
 816         engineUpdate(data);
 817     }
 818 
 819     /**
 820      * Returns the name of the algorithm for this signature object.
 821      *
 822      * @return the name of the algorithm for this signature object.
 823      */
 824     public final String getAlgorithm() {
 825         return this.algorithm;
 826     }
 827 
 828     /**
 829      * Returns a string representation of this signature object,
 830      * providing information that includes the state of the object
 831      * and the name of the algorithm used.
 832      *
 833      * @return a string representation of this signature object.
 834      */
 835     public String toString() {
 836         String initState = "";
 837         switch (state) {
 838         case UNINITIALIZED:
 839             initState = "<not initialized>";
 840             break;
 841         case VERIFY:
 842             initState = "<initialized for verifying>";
 843             break;
 844         case SIGN:
 845             initState = "<initialized for signing>";
 846             break;
 847         }
 848         return "Signature object: " + getAlgorithm() + initState;
 849     }
 850 
 851     /**
 852      * Sets the specified algorithm parameter to the specified value.
 853      * This method supplies a general-purpose mechanism through
 854      * which it is possible to set the various parameters of this object.
 855      * A parameter may be any settable parameter for the algorithm, such as
 856      * a parameter size, or a source of random bits for signature generation
 857      * (if appropriate), or an indication of whether or not to perform
 858      * a specific but optional computation. A uniform algorithm-specific
 859      * naming scheme for each parameter is desirable but left unspecified
 860      * at this time.
 861      *
 862      * @param param the string identifier of the parameter.
 863      * @param value the parameter value.
 864      *
 865      * @exception InvalidParameterException if {@code param} is an
 866      * invalid parameter for this signature algorithm engine,
 867      * the parameter is already set
 868      * and cannot be set again, a security exception occurs, and so on.
 869      *
 870      * @see #getParameter
 871      *
 872      * @deprecated Use
 873      * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
 874      * setParameter}.
 875      */
 876     @Deprecated
 877     public final void setParameter(String param, Object value)
 878             throws InvalidParameterException {
 879         engineSetParameter(param, value);
 880     }
 881 
 882     /**
 883      * Initializes this signature engine with the specified parameter set.
 884      *
 885      * @param params the parameters
 886      *
 887      * @exception InvalidAlgorithmParameterException if the given parameters
 888      * are inappropriate for this signature engine
 889      *
 890      * @see #getParameters
 891      */
 892     public final void setParameter(AlgorithmParameterSpec params)
 893             throws InvalidAlgorithmParameterException {
 894         engineSetParameter(params);
 895     }
 896 
 897     /**
 898      * Returns the parameters used with this signature object.
 899      *
 900      * <p>The returned parameters may be the same that were used to initialize
 901      * this signature, or may contain a combination of default and randomly
 902      * generated parameter values used by the underlying signature
 903      * implementation if this signature requires algorithm parameters but
 904      * was not initialized with any.
 905      *
 906      * @return the parameters used with this signature, or null if this
 907      * signature does not use any parameters.
 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 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("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 }