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