1 /* 2 * Copyright (c) 1996, 2020, 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.util.*; 29 import java.io.ByteArrayOutputStream; 30 import java.io.PrintStream; 31 import java.nio.ByteBuffer; 32 33 import sun.security.jca.GetInstance; 34 import sun.security.util.Debug; 35 import sun.security.util.MessageDigestSpi2; 36 37 import javax.crypto.SecretKey; 38 39 /** 40 * This MessageDigest class provides applications the functionality of a 41 * message digest algorithm, such as SHA-1 or SHA-256. 42 * Message digests are secure one-way hash functions that take arbitrary-sized 43 * data and output a fixed-length hash value. 44 * 45 * <p>A MessageDigest object starts out initialized. The data is 46 * processed through it using the {@link #update(byte) update} 47 * methods. At any point {@link #reset() reset} can be called 48 * to reset the digest. Once all the data to be updated has been 49 * updated, one of the {@link #digest() digest} methods should 50 * be called to complete the hash computation. 51 * 52 * <p>The {@code digest} method can be called once for a given number 53 * of updates. After {@code digest} has been called, the MessageDigest 54 * object is reset to its initialized state. 55 * 56 * <p>Implementations are free to implement the Cloneable interface. 57 * Client applications can test cloneability by attempting cloning 58 * and catching the CloneNotSupportedException: 59 * 60 * <pre>{@code 61 * MessageDigest md = MessageDigest.getInstance("SHA-256"); 62 * 63 * try { 64 * md.update(toChapter1); 65 * MessageDigest tc1 = md.clone(); 66 * byte[] toChapter1Digest = tc1.digest(); 67 * md.update(toChapter2); 68 * ...etc. 69 * } catch (CloneNotSupportedException cnse) { 70 * throw new DigestException("couldn't make digest of partial content"); 71 * } 72 * }</pre> 73 * 74 * <p>Note that if a given implementation is not cloneable, it is 75 * still possible to compute intermediate digests by instantiating 76 * several instances, if the number of digests is known in advance. 77 * 78 * <p>Note that this class is abstract and extends from 79 * {@code MessageDigestSpi} for historical reasons. 80 * Application developers should only take notice of the methods defined in 81 * this {@code MessageDigest} class; all the methods in 82 * the superclass are intended for cryptographic service providers who wish to 83 * supply their own implementations of message digest algorithms. 84 * 85 * <p> Every implementation of the Java platform is required to support 86 * the following standard {@code MessageDigest} algorithms: 87 * <ul> 88 * <li>{@code SHA-1}</li> 89 * <li>{@code SHA-256}</li> 90 * </ul> 91 * These algorithms are described in the <a href= 92 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 93 * MessageDigest section</a> of the 94 * Java Security Standard Algorithm Names Specification. 95 * Consult the release documentation for your implementation to see if any 96 * other algorithms are supported. 97 * 98 * @author Benjamin Renaud 99 * @since 1.1 100 * 101 * @see DigestInputStream 102 * @see DigestOutputStream 103 */ 104 105 public abstract class MessageDigest extends MessageDigestSpi { 106 107 private static final Debug pdebug = 108 Debug.getInstance("provider", "Provider"); 109 private static final boolean skipDebug = 110 Debug.isOn("engine=") && !Debug.isOn("messagedigest"); 111 112 private String algorithm; 113 114 // The state of this digest 115 private static final int INITIAL = 0; 116 private static final int IN_PROGRESS = 1; 117 private int state = INITIAL; 118 119 // The provider 120 private Provider provider; 121 122 /** 123 * Creates a message digest with the specified algorithm name. 124 * 125 * @param algorithm the standard name of the digest algorithm. 126 * See the MessageDigest section in the <a href= 127 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 128 * Java Security Standard Algorithm Names Specification</a> 129 * for information about standard algorithm names. 130 */ MessageDigest(String algorithm)131 protected MessageDigest(String algorithm) { 132 this.algorithm = algorithm; 133 } 134 135 // private constructor used only by Delegate class MessageDigest(String algorithm, Provider p)136 private MessageDigest(String algorithm, Provider p) { 137 this.algorithm = algorithm; 138 this.provider = p; 139 } 140 141 /** 142 * Returns a MessageDigest object that implements the specified digest 143 * algorithm. 144 * 145 * <p> This method traverses the list of registered security Providers, 146 * starting with the most preferred Provider. 147 * A new MessageDigest object encapsulating the 148 * MessageDigestSpi implementation from the first 149 * Provider that supports the specified algorithm is returned. 150 * 151 * <p> Note that the list of registered providers may be retrieved via 152 * the {@link Security#getProviders() Security.getProviders()} method. 153 * 154 * @implNote 155 * The JDK Reference Implementation additionally uses the 156 * {@code jdk.security.provider.preferred} 157 * {@link Security#getProperty(String) Security} property to determine 158 * the preferred provider order for the specified algorithm. This 159 * may be different than the order of providers returned by 160 * {@link Security#getProviders() Security.getProviders()}. 161 * 162 * @param algorithm the name of the algorithm requested. 163 * See the MessageDigest section in the <a href= 164 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 165 * Java Security Standard Algorithm Names Specification</a> 166 * for information about standard algorithm names. 167 * 168 * @return a {@code MessageDigest} object that implements the 169 * specified algorithm 170 * 171 * @throws NoSuchAlgorithmException if no {@code Provider} supports a 172 * {@code MessageDigestSpi} implementation for the 173 * specified algorithm 174 * 175 * @throws NullPointerException if {@code algorithm} is {@code null} 176 * 177 * @see Provider 178 */ getInstance(String algorithm)179 public static MessageDigest getInstance(String algorithm) 180 throws NoSuchAlgorithmException 181 { 182 Objects.requireNonNull(algorithm, "null algorithm name"); 183 MessageDigest md; 184 185 GetInstance.Instance instance = GetInstance.getInstance("MessageDigest", 186 MessageDigestSpi.class, algorithm); 187 if (instance.impl instanceof MessageDigest messageDigest) { 188 md = messageDigest; 189 md.provider = instance.provider; 190 } else { 191 md = Delegate.of((MessageDigestSpi)instance.impl, algorithm, 192 instance.provider); 193 } 194 195 if (!skipDebug && pdebug != null) { 196 pdebug.println("MessageDigest." + algorithm + 197 " algorithm from: " + md.provider.getName()); 198 } 199 200 return md; 201 } 202 203 /** 204 * Returns a MessageDigest object that implements the specified digest 205 * algorithm. 206 * 207 * <p> A new MessageDigest object encapsulating the 208 * MessageDigestSpi implementation from the specified provider 209 * is returned. The specified provider must be registered 210 * in the security provider list. 211 * 212 * <p> Note that the list of registered providers may be retrieved via 213 * the {@link Security#getProviders() Security.getProviders()} method. 214 * 215 * @param algorithm the name of the algorithm requested. 216 * See the MessageDigest section in the <a href= 217 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 218 * Java Security Standard Algorithm Names Specification</a> 219 * for information about standard algorithm names. 220 * 221 * @param provider the name of the provider. 222 * 223 * @return a {@code MessageDigest} object that implements the 224 * specified algorithm 225 * 226 * @throws IllegalArgumentException if the provider name is {@code null} 227 * or empty 228 * 229 * @throws NoSuchAlgorithmException if a {@code MessageDigestSpi} 230 * implementation for the specified algorithm is not 231 * available from the specified provider 232 * 233 * @throws NoSuchProviderException if the specified provider is not 234 * registered in the security provider list 235 * 236 * @throws NullPointerException if {@code algorithm} is {@code null} 237 * 238 * @see Provider 239 */ getInstance(String algorithm, String provider)240 public static MessageDigest getInstance(String algorithm, String provider) 241 throws NoSuchAlgorithmException, NoSuchProviderException 242 { 243 Objects.requireNonNull(algorithm, "null algorithm name"); 244 if (provider == null || provider.isEmpty()) 245 throw new IllegalArgumentException("missing provider"); 246 247 MessageDigest md; 248 GetInstance.Instance instance = GetInstance.getInstance("MessageDigest", 249 MessageDigestSpi.class, algorithm, provider); 250 if (instance.impl instanceof MessageDigest messageDigest) { 251 md = messageDigest; 252 md.provider = instance.provider; 253 } else { 254 md = Delegate.of((MessageDigestSpi)instance.impl, algorithm, 255 instance.provider); 256 } 257 return md; 258 } 259 260 /** 261 * Returns a MessageDigest object that implements the specified digest 262 * algorithm. 263 * 264 * <p> A new MessageDigest object encapsulating the 265 * MessageDigestSpi implementation from the specified Provider 266 * object is returned. Note that the specified Provider object 267 * does not have to be registered in the provider list. 268 * 269 * @param algorithm the name of the algorithm requested. 270 * See the MessageDigest section in the <a href= 271 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 272 * Java Security Standard Algorithm Names Specification</a> 273 * for information about standard algorithm names. 274 * 275 * @param provider the provider. 276 * 277 * @return a {@code MessageDigest} object that implements the 278 * specified algorithm 279 * 280 * @throws IllegalArgumentException if the specified provider is 281 * {@code null} 282 * 283 * @throws NoSuchAlgorithmException if a {@code MessageDigestSpi} 284 * implementation for the specified algorithm is not available 285 * from the specified {@code Provider} object 286 * 287 * @throws NullPointerException if {@code algorithm} is {@code null} 288 * 289 * @see Provider 290 * 291 * @since 1.4 292 */ getInstance(String algorithm, Provider provider)293 public static MessageDigest getInstance(String algorithm, 294 Provider provider) 295 throws NoSuchAlgorithmException 296 { 297 Objects.requireNonNull(algorithm, "null algorithm name"); 298 if (provider == null) 299 throw new IllegalArgumentException("missing provider"); 300 Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); 301 if (objs[0] instanceof MessageDigest md) { 302 md.provider = (Provider)objs[1]; 303 return md; 304 } else { 305 MessageDigest delegate = 306 Delegate.of((MessageDigestSpi)objs[0], algorithm, 307 (Provider)objs[1]); 308 return delegate; 309 } 310 } 311 312 /** 313 * Returns the provider of this message digest object. 314 * 315 * @return the provider of this message digest object 316 */ getProvider()317 public final Provider getProvider() { 318 return this.provider; 319 } 320 321 /** 322 * Updates the digest using the specified byte. 323 * 324 * @param input the byte with which to update the digest. 325 */ update(byte input)326 public void update(byte input) { 327 engineUpdate(input); 328 state = IN_PROGRESS; 329 } 330 331 /** 332 * Updates the digest using the specified array of bytes, starting 333 * at the specified offset. 334 * 335 * @param input the array of bytes. 336 * 337 * @param offset the offset to start from in the array of bytes. 338 * 339 * @param len the number of bytes to use, starting at 340 * {@code offset}. 341 */ update(byte[] input, int offset, int len)342 public void update(byte[] input, int offset, int len) { 343 if (input == null) { 344 throw new IllegalArgumentException("No input buffer given"); 345 } 346 if (input.length - offset < len) { 347 throw new IllegalArgumentException("Input buffer too short"); 348 } 349 engineUpdate(input, offset, len); 350 state = IN_PROGRESS; 351 } 352 353 /** 354 * Updates the digest using the specified array of bytes. 355 * 356 * @param input the array of bytes. 357 */ update(byte[] input)358 public void update(byte[] input) { 359 engineUpdate(input, 0, input.length); 360 state = IN_PROGRESS; 361 } 362 363 /** 364 * Update the digest using the specified ByteBuffer. The digest is 365 * updated using the {@code input.remaining()} bytes starting 366 * at {@code input.position()}. 367 * Upon return, the buffer's position will be equal to its limit; 368 * its limit will not have changed. 369 * 370 * @param input the ByteBuffer 371 * @since 1.5 372 */ update(ByteBuffer input)373 public final void update(ByteBuffer input) { 374 if (input == null) { 375 throw new NullPointerException(); 376 } 377 engineUpdate(input); 378 state = IN_PROGRESS; 379 } 380 381 /** 382 * Completes the hash computation by performing final operations 383 * such as padding. The digest is reset after this call is made. 384 * 385 * @return the array of bytes for the resulting hash value. 386 */ digest()387 public byte[] digest() { 388 /* Resetting is the responsibility of implementors. */ 389 byte[] result = engineDigest(); 390 state = INITIAL; 391 return result; 392 } 393 394 /** 395 * Completes the hash computation by performing final operations 396 * such as padding. The digest is reset after this call is made. 397 * 398 * @param buf output buffer for the computed digest 399 * 400 * @param offset offset into the output buffer to begin storing the digest 401 * 402 * @param len number of bytes within buf allotted for the digest 403 * 404 * @return the number of bytes placed into {@code buf} 405 * 406 * @throws DigestException if an error occurs. 407 */ digest(byte[] buf, int offset, int len)408 public int digest(byte[] buf, int offset, int len) throws DigestException { 409 if (buf == null) { 410 throw new IllegalArgumentException("No output buffer given"); 411 } 412 if (buf.length - offset < len) { 413 throw new IllegalArgumentException 414 ("Output buffer too small for specified offset and length"); 415 } 416 int numBytes = engineDigest(buf, offset, len); 417 state = INITIAL; 418 return numBytes; 419 } 420 421 /** 422 * Performs a final update on the digest using the specified array 423 * of bytes, then completes the digest computation. That is, this 424 * method first calls {@link #update(byte[]) update(input)}, 425 * passing the <i>input</i> array to the {@code update} method, 426 * then calls {@link #digest() digest()}. 427 * 428 * @param input the input to be updated before the digest is 429 * completed. 430 * 431 * @return the array of bytes for the resulting hash value. 432 */ digest(byte[] input)433 public byte[] digest(byte[] input) { 434 update(input); 435 return digest(); 436 } 437 getProviderName()438 private String getProviderName() { 439 return (provider == null) ? "(no provider)" : provider.getName(); 440 } 441 442 /** 443 * Returns a string representation of this message digest object. 444 */ toString()445 public String toString() { 446 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 447 PrintStream p = new PrintStream(baos); 448 p.print(algorithm+" Message Digest from "+getProviderName()+", "); 449 switch (state) { 450 case INITIAL: 451 p.print("<initialized>"); 452 break; 453 case IN_PROGRESS: 454 p.print("<in progress>"); 455 break; 456 } 457 p.println(); 458 return (baos.toString()); 459 } 460 461 /** 462 * Compares two digests for equality. Two digests are equal if they have 463 * the same length and all bytes at corresponding positions are equal. 464 * 465 * @implNote 466 * All bytes in {@code digesta} are examined to determine equality. 467 * The calculation time depends only on the length of {@code digesta}. 468 * It does not depend on the length of {@code digestb} or the contents 469 * of {@code digesta} and {@code digestb}. 470 * 471 * @param digesta one of the digests to compare. 472 * 473 * @param digestb the other digest to compare. 474 * 475 * @return true if the digests are equal, false otherwise. 476 */ isEqual(byte[] digesta, byte[] digestb)477 public static boolean isEqual(byte[] digesta, byte[] digestb) { 478 if (digesta == digestb) return true; 479 if (digesta == null || digestb == null) { 480 return false; 481 } 482 483 int lenA = digesta.length; 484 int lenB = digestb.length; 485 486 if (lenB == 0) { 487 return lenA == 0; 488 } 489 490 int result = 0; 491 result |= lenA - lenB; 492 493 // time-constant comparison 494 for (int i = 0; i < lenA; i++) { 495 // If i >= lenB, indexB is 0; otherwise, i. 496 int indexB = ((i - lenB) >>> 31) * i; 497 result |= digesta[i] ^ digestb[indexB]; 498 } 499 return result == 0; 500 } 501 502 /** 503 * Resets the digest for further use. 504 */ reset()505 public void reset() { 506 engineReset(); 507 state = INITIAL; 508 } 509 510 /** 511 * Returns a string that identifies the algorithm, independent of 512 * implementation details. The name should be a standard 513 * Java Security name (such as "SHA-256"). 514 * See the MessageDigest section in the <a href= 515 * "{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms"> 516 * Java Security Standard Algorithm Names Specification</a> 517 * for information about standard algorithm names. 518 * 519 * @return the name of the algorithm 520 */ getAlgorithm()521 public final String getAlgorithm() { 522 return this.algorithm; 523 } 524 525 /** 526 * Returns the length of the digest in bytes, or 0 if this operation is 527 * not supported by the provider and the implementation is not cloneable. 528 * 529 * @return the digest length in bytes, or 0 if this operation is not 530 * supported by the provider and the implementation is not cloneable. 531 * 532 * @since 1.2 533 */ getDigestLength()534 public final int getDigestLength() { 535 int digestLen = engineGetDigestLength(); 536 if (digestLen == 0) { 537 try { 538 MessageDigest md = (MessageDigest)clone(); 539 byte[] digest = md.digest(); 540 return digest.length; 541 } catch (CloneNotSupportedException e) { 542 return digestLen; 543 } 544 } 545 return digestLen; 546 } 547 548 /** 549 * Returns a clone if the implementation is cloneable. 550 * 551 * @return a clone if the implementation is cloneable. 552 * 553 * @throws CloneNotSupportedException if this is called on an 554 * implementation that does not support {@code Cloneable}. 555 */ clone()556 public Object clone() throws CloneNotSupportedException { 557 if (this instanceof Cloneable) { 558 return super.clone(); 559 } else { 560 throw new CloneNotSupportedException(); 561 } 562 } 563 564 565 /* 566 * The following class allows providers to extend from MessageDigestSpi 567 * rather than from MessageDigest. It represents a MessageDigest with an 568 * encapsulated, provider-supplied SPI object (of type MessageDigestSpi). 569 * If the provider implementation is an instance of MessageDigestSpi, 570 * the getInstance() methods above return an instance of this class, with 571 * the SPI object encapsulated. 572 * 573 * Note: All SPI methods from the original MessageDigest class have been 574 * moved up the hierarchy into a new class (MessageDigestSpi), which has 575 * been interposed in the hierarchy between the API (MessageDigest) 576 * and its original parent (Object). 577 */ 578 579 private static class Delegate extends MessageDigest 580 implements MessageDigestSpi2 { 581 // use this class for spi objects which implements Cloneable 582 private static final class CloneableDelegate extends Delegate 583 implements Cloneable { 584 CloneableDelegate(MessageDigestSpi digestSpi, String algorithm, Provider p)585 private CloneableDelegate(MessageDigestSpi digestSpi, 586 String algorithm, Provider p) { 587 super(digestSpi, algorithm, p); 588 } 589 } 590 591 // The provider implementation (delegate) 592 private final MessageDigestSpi digestSpi; 593 594 // factory method used by MessageDigest class to create Delegate objs of(MessageDigestSpi digestSpi, String algo, Provider p)595 static Delegate of(MessageDigestSpi digestSpi, String algo, 596 Provider p) { 597 Objects.requireNonNull(digestSpi); 598 boolean isCloneable = (digestSpi instanceof Cloneable); 599 // Spi impls from SunPKCS11 provider implement Cloneable but their 600 // clone() may throw CloneNotSupportException 601 if (isCloneable && p.getName().startsWith("SunPKCS11") && 602 p.getClass().getModule().getName().equals 603 ("jdk.crypto.cryptoki")) { 604 try { 605 digestSpi.clone(); 606 } catch (CloneNotSupportedException cnse) { 607 isCloneable = false; 608 } 609 } 610 return (isCloneable? new CloneableDelegate(digestSpi, algo, p) : 611 new Delegate(digestSpi, algo, p)); 612 } 613 614 // private constructor Delegate(MessageDigestSpi digestSpi, String algorithm, Provider p)615 private Delegate(MessageDigestSpi digestSpi, String algorithm, 616 Provider p) { 617 super(algorithm, p); 618 this.digestSpi = digestSpi; 619 } 620 621 /** 622 * Returns a clone if the delegate is cloneable. 623 * 624 * @return a clone if the delegate is cloneable. 625 * 626 * @throws CloneNotSupportedException if this is called on a 627 * delegate that does not support {@code Cloneable}. 628 */ 629 @Override clone()630 public Object clone() throws CloneNotSupportedException { 631 if (this instanceof Cloneable) { 632 // Because 'algorithm', 'provider', and 'state' are private 633 // members of our supertype, we must perform a cast to 634 // access them. 635 MessageDigest that = new CloneableDelegate( 636 (MessageDigestSpi)digestSpi.clone(), 637 ((MessageDigest)this).algorithm, 638 ((MessageDigest)this).provider); 639 that.state = ((MessageDigest)this).state; 640 return that; 641 } else { 642 throw new CloneNotSupportedException(); 643 } 644 } 645 646 @Override engineGetDigestLength()647 protected int engineGetDigestLength() { 648 return digestSpi.engineGetDigestLength(); 649 } 650 651 @Override engineUpdate(byte input)652 protected void engineUpdate(byte input) { 653 digestSpi.engineUpdate(input); 654 } 655 656 @Override engineUpdate(byte[] input, int offset, int len)657 protected void engineUpdate(byte[] input, int offset, int len) { 658 digestSpi.engineUpdate(input, offset, len); 659 } 660 661 @Override engineUpdate(ByteBuffer input)662 protected void engineUpdate(ByteBuffer input) { 663 digestSpi.engineUpdate(input); 664 } 665 666 @Override engineUpdate(SecretKey key)667 public void engineUpdate(SecretKey key) throws InvalidKeyException { 668 if (digestSpi instanceof MessageDigestSpi2) { 669 ((MessageDigestSpi2)digestSpi).engineUpdate(key); 670 } else { 671 throw new UnsupportedOperationException 672 ("Digest does not support update of SecretKey object"); 673 } 674 } 675 676 @Override engineDigest()677 protected byte[] engineDigest() { 678 return digestSpi.engineDigest(); 679 } 680 681 @Override engineDigest(byte[] buf, int offset, int len)682 protected int engineDigest(byte[] buf, int offset, int len) 683 throws DigestException { 684 return digestSpi.engineDigest(buf, offset, len); 685 } 686 687 @Override engineReset()688 protected void engineReset() { 689 digestSpi.engineReset(); 690 } 691 } 692 } 693