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