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