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