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