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