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