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