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.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"); 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 */ 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 * @implNote 153 * The JDK Reference Implementation additionally uses the 154 * {@code jdk.security.provider.preferred} 155 * {@link Security#getProperty(String) Security} property to determine 156 * the preferred provider order for the specified algorithm. This 157 * may be different than the order of providers returned by 158 * {@link Security#getProviders() Security.getProviders()}. 159 * 160 * @param algorithm the name of the algorithm requested. 161 * See the MessageDigest section in the <a href= 162 * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> 163 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 164 * for information about standard algorithm names. 165 * 166 * @return a Message Digest object that implements the specified algorithm. 167 * 168 * @exception NoSuchAlgorithmException if no Provider supports a 169 * MessageDigestSpi implementation for the 170 * specified algorithm. 171 * 172 * @see Provider 173 */ 174 public static MessageDigest getInstance(String algorithm) 175 throws NoSuchAlgorithmException { 176 try { 177 MessageDigest md; 178 Object[] objs = Security.getImpl(algorithm, "MessageDigest", 179 (String)null); 180 if (objs[0] instanceof MessageDigest) { 181 md = (MessageDigest)objs[0]; 182 } else { 183 md = new Delegate((MessageDigestSpi)objs[0], algorithm); 184 } 185 md.provider = (Provider)objs[1]; 186 187 if (!skipDebug && pdebug != null) { 188 pdebug.println("MessageDigest." + algorithm + 189 " algorithm from: " + md.provider.getName()); 190 } 191 192 return md; 193 194 } catch(NoSuchProviderException e) { 195 throw new NoSuchAlgorithmException(algorithm + " not found"); 196 } 197 } 198 199 /** 200 * Returns a MessageDigest object that implements the specified digest 201 * algorithm. 202 * 203 * <p> A new MessageDigest object encapsulating the 204 * MessageDigestSpi implementation from the specified provider 205 * is returned. The specified provider must be registered 206 * in the security provider list. 207 * 208 * <p> Note that the list of registered providers may be retrieved via 209 * the {@link Security#getProviders() Security.getProviders()} method. 210 * 211 * @param algorithm the name of the algorithm requested. 212 * See the MessageDigest section in the <a href= 213 * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> 214 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 215 * for information about standard algorithm names. 216 * 217 * @param provider the name of the provider. 218 * 219 * @return a MessageDigest object that implements the specified algorithm. 220 * 221 * @exception NoSuchAlgorithmException if a MessageDigestSpi 222 * implementation for the specified algorithm is not 223 * available from the specified provider. 224 * 225 * @exception NoSuchProviderException if the specified provider is not 226 * registered in the security provider list. 227 * 228 * @exception IllegalArgumentException if the provider name is null 229 * or empty. 230 * 231 * @see Provider 232 */ 233 public static MessageDigest getInstance(String algorithm, String provider) 234 throws NoSuchAlgorithmException, NoSuchProviderException 235 { 236 if (provider == null || provider.length() == 0) 237 throw new IllegalArgumentException("missing provider"); 238 Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); 239 if (objs[0] instanceof MessageDigest) { 240 MessageDigest md = (MessageDigest)objs[0]; 241 md.provider = (Provider)objs[1]; 242 return md; 243 } else { 244 MessageDigest delegate = 245 new Delegate((MessageDigestSpi)objs[0], algorithm); 246 delegate.provider = (Provider)objs[1]; 247 return delegate; 248 } 249 } 250 251 /** 252 * Returns a MessageDigest object that implements the specified digest 253 * algorithm. 254 * 255 * <p> A new MessageDigest object encapsulating the 256 * MessageDigestSpi implementation from the specified Provider 257 * object is returned. Note that the specified Provider object 258 * does not have to be registered in the provider list. 259 * 260 * @param algorithm the name of the algorithm requested. 261 * See the MessageDigest section in the <a href= 262 * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> 263 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 264 * for information about standard algorithm names. 265 * 266 * @param provider the provider. 267 * 268 * @return a MessageDigest object that implements the specified algorithm. 269 * 270 * @exception NoSuchAlgorithmException if a MessageDigestSpi 271 * implementation for the specified algorithm is not available 272 * from the specified Provider object. 273 * 274 * @exception IllegalArgumentException if the specified provider is null. 275 * 276 * @see Provider 277 * 278 * @since 1.4 279 */ 280 public static MessageDigest getInstance(String algorithm, 281 Provider provider) 282 throws NoSuchAlgorithmException 283 { 284 if (provider == null) 285 throw new IllegalArgumentException("missing provider"); 286 Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); 287 if (objs[0] instanceof MessageDigest) { 288 MessageDigest md = (MessageDigest)objs[0]; 289 md.provider = (Provider)objs[1]; 290 return md; 291 } else { 292 MessageDigest delegate = 293 new Delegate((MessageDigestSpi)objs[0], algorithm); 294 delegate.provider = (Provider)objs[1]; 295 return delegate; 296 } 297 } 298 299 /** 300 * Returns the provider of this message digest object. 301 * 302 * @return the provider of this message digest object 303 */ 304 public final Provider getProvider() { 305 return this.provider; 306 } 307 308 /** 309 * Updates the digest using the specified byte. 310 * 311 * @param input the byte with which to update the digest. 312 */ 313 public void update(byte input) { 314 engineUpdate(input); 315 state = IN_PROGRESS; 316 } 317 318 /** 319 * Updates the digest using the specified array of bytes, starting 320 * at the specified offset. 321 * 322 * @param input the array of bytes. 323 * 324 * @param offset the offset to start from in the array of bytes. 325 * 326 * @param len the number of bytes to use, starting at 327 * {@code offset}. 328 */ 329 public void update(byte[] input, int offset, int len) { 330 if (input == null) { 331 throw new IllegalArgumentException("No input buffer given"); 332 } 333 if (input.length - offset < len) { 334 throw new IllegalArgumentException("Input buffer too short"); 335 } 336 engineUpdate(input, offset, len); 337 state = IN_PROGRESS; 338 } 339 340 /** 341 * Updates the digest using the specified array of bytes. 342 * 343 * @param input the array of bytes. 344 */ 345 public void update(byte[] input) { 346 engineUpdate(input, 0, input.length); 347 state = IN_PROGRESS; 348 } 349 350 /** 351 * Update the digest using the specified ByteBuffer. The digest is 352 * updated using the {@code input.remaining()} bytes starting 353 * at {@code input.position()}. 354 * Upon return, the buffer's position will be equal to its limit; 355 * its limit will not have changed. 356 * 357 * @param input the ByteBuffer 358 * @since 1.5 359 */ 360 public final void update(ByteBuffer input) { 361 if (input == null) { 362 throw new NullPointerException(); 363 } 364 engineUpdate(input); 365 state = IN_PROGRESS; 366 } 367 368 /** 369 * Completes the hash computation by performing final operations 370 * such as padding. The digest is reset after this call is made. 371 * 372 * @return the array of bytes for the resulting hash value. 373 */ 374 public byte[] digest() { 375 /* Resetting is the responsibility of implementors. */ 376 byte[] result = engineDigest(); 377 state = INITIAL; 378 return result; 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 * @param buf output buffer for the computed digest 386 * 387 * @param offset offset into the output buffer to begin storing the digest 388 * 389 * @param len number of bytes within buf allotted for the digest 390 * 391 * @return the number of bytes placed into {@code buf} 392 * 393 * @exception DigestException if an error occurs. 394 */ 395 public int digest(byte[] buf, int offset, int len) throws DigestException { 396 if (buf == null) { 397 throw new IllegalArgumentException("No output buffer given"); 398 } 399 if (buf.length - offset < len) { 400 throw new IllegalArgumentException 401 ("Output buffer too small for specified offset and length"); 402 } 403 int numBytes = engineDigest(buf, offset, len); 404 state = INITIAL; 405 return numBytes; 406 } 407 408 /** 409 * Performs a final update on the digest using the specified array 410 * of bytes, then completes the digest computation. That is, this 411 * method first calls {@link #update(byte[]) update(input)}, 412 * passing the <i>input</i> array to the {@code update} method, 413 * then calls {@link #digest() digest()}. 414 * 415 * @param input the input to be updated before the digest is 416 * completed. 417 * 418 * @return the array of bytes for the resulting hash value. 419 */ 420 public byte[] digest(byte[] input) { 421 update(input); 422 return digest(); 423 } 424 425 /** 426 * Returns a string representation of this message digest object. 427 */ 428 public String toString() { 429 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 430 PrintStream p = new PrintStream(baos); 431 p.print(algorithm+" Message Digest from "+provider.getName()+", "); 432 switch (state) { 433 case INITIAL: 434 p.print("<initialized>"); 435 break; 436 case IN_PROGRESS: 437 p.print("<in progress>"); 438 break; 439 } 440 p.println(); 441 return (baos.toString()); 442 } 443 444 /** 445 * Compares two digests for equality. Two digests are equal if they have 446 * the same length and all bytes at corresponding positions are equal. 447 * 448 * @implNote 449 * If the digests are the same length, all bytes are examined to 450 * determine equality. 451 * 452 * @param digesta one of the digests to compare. 453 * 454 * @param digestb the other digest to compare. 455 * 456 * @return true if the digests are equal, false otherwise. 457 */ 458 public static boolean isEqual(byte[] digesta, byte[] digestb) { 459 if (digesta == digestb) return true; 460 if (digesta == null || digestb == null) { 461 return false; 462 } 463 if (digesta.length != digestb.length) { 464 return false; 465 } 466 467 int result = 0; 468 // time-constant comparison 469 for (int i = 0; i < digesta.length; i++) { 470 result |= digesta[i] ^ digestb[i]; 471 } 472 return result == 0; 473 } 474 475 /** 476 * Resets the digest for further use. 477 */ 478 public void reset() { 479 engineReset(); 480 state = INITIAL; 481 } 482 483 /** 484 * Returns a string that identifies the algorithm, independent of 485 * implementation details. The name should be a standard 486 * Java Security name (such as "SHA", "MD5", and so on). 487 * See the MessageDigest section in the <a href= 488 * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> 489 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 490 * for information about standard algorithm names. 491 * 492 * @return the name of the algorithm 493 */ 494 public final String getAlgorithm() { 495 return this.algorithm; 496 } 497 498 /** 499 * Returns the length of the digest in bytes, or 0 if this operation is 500 * not supported by the provider and the implementation is not cloneable. 501 * 502 * @return the digest length in bytes, or 0 if this operation is not 503 * supported by the provider and the implementation is not cloneable. 504 * 505 * @since 1.2 506 */ 507 public final int getDigestLength() { 508 int digestLen = engineGetDigestLength(); 509 if (digestLen == 0) { 510 try { 511 MessageDigest md = (MessageDigest)clone(); 512 byte[] digest = md.digest(); 513 return digest.length; 514 } catch (CloneNotSupportedException e) { 515 return digestLen; 516 } 517 } 518 return digestLen; 519 } 520 521 /** 522 * Returns a clone if the implementation is cloneable. 523 * 524 * @return a clone if the implementation is cloneable. 525 * 526 * @exception CloneNotSupportedException if this is called on an 527 * implementation that does not support {@code Cloneable}. 528 */ 529 public Object clone() throws CloneNotSupportedException { 530 if (this instanceof Cloneable) { 531 return super.clone(); 532 } else { 533 throw new CloneNotSupportedException(); 534 } 535 } 536 537 538 539 540 /* 541 * The following class allows providers to extend from MessageDigestSpi 542 * rather than from MessageDigest. It represents a MessageDigest with an 543 * encapsulated, provider-supplied SPI object (of type MessageDigestSpi). 544 * If the provider implementation is an instance of MessageDigestSpi, 545 * the getInstance() methods above return an instance of this class, with 546 * the SPI object encapsulated. 547 * 548 * Note: All SPI methods from the original MessageDigest class have been 549 * moved up the hierarchy into a new class (MessageDigestSpi), which has 550 * been interposed in the hierarchy between the API (MessageDigest) 551 * and its original parent (Object). 552 */ 553 554 static class Delegate extends MessageDigest implements MessageDigestSpi2 { 555 556 // The provider implementation (delegate) 557 private MessageDigestSpi digestSpi; 558 559 // constructor 560 public Delegate(MessageDigestSpi digestSpi, String algorithm) { 561 super(algorithm); 562 this.digestSpi = digestSpi; 563 } 564 565 /** 566 * Returns a clone if the delegate is cloneable. 567 * 568 * @return a clone if the delegate is cloneable. 569 * 570 * @exception CloneNotSupportedException if this is called on a 571 * delegate that does not support {@code Cloneable}. 572 */ 573 public Object clone() throws CloneNotSupportedException { 574 if (digestSpi instanceof Cloneable) { 575 MessageDigestSpi digestSpiClone = 576 (MessageDigestSpi)digestSpi.clone(); 577 // Because 'algorithm', 'provider', and 'state' are private 578 // members of our supertype, we must perform a cast to 579 // access them. 580 MessageDigest that = 581 new Delegate(digestSpiClone, 582 ((MessageDigest)this).algorithm); 583 that.provider = ((MessageDigest)this).provider; 584 that.state = ((MessageDigest)this).state; 585 return that; 586 } else { 587 throw new CloneNotSupportedException(); 588 } 589 } 590 591 protected int engineGetDigestLength() { 592 return digestSpi.engineGetDigestLength(); 593 } 594 595 protected void engineUpdate(byte input) { 596 digestSpi.engineUpdate(input); 597 } 598 599 protected void engineUpdate(byte[] input, int offset, int len) { 600 digestSpi.engineUpdate(input, offset, len); 601 } 602 603 protected void engineUpdate(ByteBuffer input) { 604 digestSpi.engineUpdate(input); 605 } 606 607 public void engineUpdate(SecretKey key) throws InvalidKeyException { 608 if (digestSpi instanceof MessageDigestSpi2) { 609 ((MessageDigestSpi2)digestSpi).engineUpdate(key); 610 } else { 611 throw new UnsupportedOperationException 612 ("Digest does not support update of SecretKey object"); 613 } 614 } 615 protected byte[] engineDigest() { 616 return digestSpi.engineDigest(); 617 } 618 619 protected int engineDigest(byte[] buf, int offset, int len) 620 throws DigestException { 621 return digestSpi.engineDigest(buf, offset, len); 622 } 623 624 protected void engineReset() { 625 digestSpi.engineReset(); 626 } 627 } 628 }