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