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