1 /* 2 * Copyright (c) 1996, 2016, 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"); 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 MD5}</li> 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}/../technotes/guides/security/StandardNames.html#MessageDigest"> 93 * MessageDigest section</a> of the 94 * Java Cryptography Architecture Standard Algorithm Name Documentation. 95 * Consult the release documentation for your implementation to see if any 96 * other algorithms are supported. 97 * 98 * @author Benjamin Renaud 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}/../technotes/guides/security/StandardNames.html#MessageDigest"> 127 * Java Cryptography Architecture Standard Algorithm Name Documentation</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}/../technotes/guides/security/StandardNames.html#MessageDigest"> 158 * Java Cryptography Architecture Standard Algorithm Name Documentation</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}/../technotes/guides/security/StandardNames.html#MessageDigest"> 213 * Java Cryptography Architecture Standard Algorithm Name Documentation</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.length() == 0) 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}/../technotes/guides/security/StandardNames.html#MessageDigest"> 266 * Java Cryptography Architecture Standard Algorithm Name Documentation</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 * @exception 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 /** 434 * Returns a string representation of this message digest object. 435 */ 436 public String toString() { 437 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 438 PrintStream p = new PrintStream(baos); 439 p.print(algorithm+" Message Digest from "+provider.getName()+", "); 440 switch (state) { 441 case INITIAL: 442 p.print("<initialized>"); 443 break; 444 case IN_PROGRESS: 445 p.print("<in progress>"); 446 break; 447 } 448 p.println(); 449 return (baos.toString()); 450 } 451 452 /** 453 * Compares two digests for equality. Two digests are equal if they have 454 * the same length and all bytes at corresponding positions are equal. 455 * 456 * @implNote 457 * If the digests are the same length, all bytes are examined to 458 * determine equality. 459 * 460 * @param digesta one of the digests to compare. 461 * 462 * @param digestb the other digest to compare. 463 * 464 * @return true if the digests are equal, false otherwise. 465 */ 466 public static boolean isEqual(byte[] digesta, byte[] digestb) { 467 if (digesta == digestb) return true; 468 if (digesta == null || digestb == null) { 469 return false; 470 } 471 if (digesta.length != digestb.length) { 472 return false; 473 } 474 475 int result = 0; 476 // time-constant comparison 477 for (int i = 0; i < digesta.length; i++) { 478 result |= digesta[i] ^ digestb[i]; 479 } 480 return result == 0; 481 } 482 483 /** 484 * Resets the digest for further use. 485 */ 486 public void reset() { 487 engineReset(); 488 state = INITIAL; 489 } 490 491 /** 492 * Returns a string that identifies the algorithm, independent of 493 * implementation details. The name should be a standard 494 * Java Security name (such as "SHA", "MD5", and so on). 495 * See the MessageDigest section in the <a href= 496 * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> 497 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 498 * for information about standard algorithm names. 499 * 500 * @return the name of the algorithm 501 */ 502 public final String getAlgorithm() { 503 return this.algorithm; 504 } 505 506 /** 507 * Returns the length of the digest in bytes, or 0 if this operation is 508 * not supported by the provider and the implementation is not cloneable. 509 * 510 * @return the digest length in bytes, or 0 if this operation is not 511 * supported by the provider and the implementation is not cloneable. 512 * 513 * @since 1.2 514 */ 515 public final int getDigestLength() { 516 int digestLen = engineGetDigestLength(); 517 if (digestLen == 0) { 518 try { 519 MessageDigest md = (MessageDigest)clone(); 520 byte[] digest = md.digest(); 521 return digest.length; 522 } catch (CloneNotSupportedException e) { 523 return digestLen; 524 } 525 } 526 return digestLen; 527 } 528 529 /** 530 * Returns a clone if the implementation is cloneable. 531 * 532 * @return a clone if the implementation is cloneable. 533 * 534 * @exception CloneNotSupportedException if this is called on an 535 * implementation that does not support {@code Cloneable}. 536 */ 537 public Object clone() throws CloneNotSupportedException { 538 if (this instanceof Cloneable) { 539 return super.clone(); 540 } else { 541 throw new CloneNotSupportedException(); 542 } 543 } 544 545 546 547 548 /* 549 * The following class allows providers to extend from MessageDigestSpi 550 * rather than from MessageDigest. It represents a MessageDigest with an 551 * encapsulated, provider-supplied SPI object (of type MessageDigestSpi). 552 * If the provider implementation is an instance of MessageDigestSpi, 553 * the getInstance() methods above return an instance of this class, with 554 * the SPI object encapsulated. 555 * 556 * Note: All SPI methods from the original MessageDigest class have been 557 * moved up the hierarchy into a new class (MessageDigestSpi), which has 558 * been interposed in the hierarchy between the API (MessageDigest) 559 * and its original parent (Object). 560 */ 561 562 static class Delegate extends MessageDigest implements MessageDigestSpi2 { 563 564 // The provider implementation (delegate) 565 private MessageDigestSpi digestSpi; 566 567 // constructor 568 public Delegate(MessageDigestSpi digestSpi, String algorithm) { 569 super(algorithm); 570 this.digestSpi = digestSpi; 571 } 572 573 /** 574 * Returns a clone if the delegate is cloneable. 575 * 576 * @return a clone if the delegate is cloneable. 577 * 578 * @exception CloneNotSupportedException if this is called on a 579 * delegate that does not support {@code Cloneable}. 580 */ 581 public Object clone() throws CloneNotSupportedException { 582 if (digestSpi instanceof Cloneable) { 583 MessageDigestSpi digestSpiClone = 584 (MessageDigestSpi)digestSpi.clone(); 585 // Because 'algorithm', 'provider', and 'state' are private 586 // members of our supertype, we must perform a cast to 587 // access them. 588 MessageDigest that = 589 new Delegate(digestSpiClone, 590 ((MessageDigest)this).algorithm); 591 that.provider = ((MessageDigest)this).provider; 592 that.state = ((MessageDigest)this).state; 593 return that; 594 } else { 595 throw new CloneNotSupportedException(); 596 } 597 } 598 599 protected int engineGetDigestLength() { 600 return digestSpi.engineGetDigestLength(); 601 } 602 603 protected void engineUpdate(byte input) { 604 digestSpi.engineUpdate(input); 605 } 606 607 protected void engineUpdate(byte[] input, int offset, int len) { 608 digestSpi.engineUpdate(input, offset, len); 609 } 610 611 protected void engineUpdate(ByteBuffer input) { 612 digestSpi.engineUpdate(input); 613 } 614 615 public void engineUpdate(SecretKey key) throws InvalidKeyException { 616 if (digestSpi instanceof MessageDigestSpi2) { 617 ((MessageDigestSpi2)digestSpi).engineUpdate(key); 618 } else { 619 throw new UnsupportedOperationException 620 ("Digest does not support update of SecretKey object"); 621 } 622 } 623 protected byte[] engineDigest() { 624 return digestSpi.engineDigest(); 625 } 626 627 protected int engineDigest(byte[] buf, int offset, int len) 628 throws DigestException { 629 return digestSpi.engineDigest(buf, offset, len); 630 } 631 632 protected void engineReset() { 633 digestSpi.engineReset(); 634 } 635 } 636 }