1. /*
  2. * @(#)MessageDigest.java 1.77 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.security;
  8. import java.util.*;
  9. import java.lang.*;
  10. import java.io.IOException;
  11. import java.io.ByteArrayOutputStream;
  12. import java.io.PrintStream;
  13. import java.io.InputStream;
  14. import java.io.ByteArrayInputStream;
  15. import java.nio.ByteBuffer;
  16. /**
  17. * This MessageDigest class provides applications the functionality of a
  18. * message digest algorithm, such as MD5 or SHA.
  19. * Message digests are secure one-way hash functions that take arbitrary-sized
  20. * data and output a fixed-length hash value.
  21. *
  22. * <p>A MessageDigest object starts out initialized. The data is
  23. * processed through it using the {@link #update(byte) update}
  24. * methods. At any point {@link #reset() reset} can be called
  25. * to reset the digest. Once all the data to be updated has been
  26. * updated, one of the {@link #digest() digest} methods should
  27. * be called to complete the hash computation.
  28. *
  29. * <p>The <code>digest</code> method can be called once for a given number
  30. * of updates. After <code>digest</code> has been called, the MessageDigest
  31. * object is reset to its initialized state.
  32. *
  33. * <p>Implementations are free to implement the Cloneable interface.
  34. * Client applications can test cloneability by attempting cloning
  35. * and catching the CloneNotSupportedException: <p>
  36. *
  37. * <pre>
  38. * MessageDigest md = MessageDigest.getInstance("SHA");
  39. *
  40. * try {
  41. * md.update(toChapter1);
  42. * MessageDigest tc1 = md.clone();
  43. * byte[] toChapter1Digest = tc1.digest();
  44. * md.update(toChapter2);
  45. * ...etc.
  46. * } catch (CloneNotSupportedException cnse) {
  47. * throw new DigestException("couldn't make digest of partial content");
  48. * }
  49. * </pre>
  50. *
  51. * <p>Note that if a given implementation is not cloneable, it is
  52. * still possible to compute intermediate digests by instantiating
  53. * several instances, if the number of digests is known in advance.
  54. *
  55. * <p>Note that this class is abstract and extends from
  56. * <code>MessageDigestSpi</code> for historical reasons.
  57. * Application developers should only take notice of the methods defined in
  58. * this <code>MessageDigest</code> class; all the methods in
  59. * the superclass are intended for cryptographic service providers who wish to
  60. * supply their own implementations of message digest algorithms.
  61. *
  62. * @author Benjamin Renaud
  63. *
  64. * @version 1.77, 12/19/03
  65. *
  66. * @see DigestInputStream
  67. * @see DigestOutputStream
  68. */
  69. public abstract class MessageDigest extends MessageDigestSpi {
  70. private String algorithm;
  71. // The state of this digest
  72. private static final int INITIAL = 0;
  73. private static final int IN_PROGRESS = 1;
  74. private int state = INITIAL;
  75. // The provider
  76. private Provider provider;
  77. /**
  78. * Creates a message digest with the specified algorithm name.
  79. *
  80. * @param algorithm the standard name of the digest algorithm.
  81. * See Appendix A in the <a href=
  82. * "../../../guide/security/CryptoSpec.html#AppA">
  83. * Java Cryptography Architecture API Specification & Reference </a>
  84. * for information about standard algorithm names.
  85. */
  86. protected MessageDigest(String algorithm) {
  87. this.algorithm = algorithm;
  88. }
  89. /**
  90. * Generates a MessageDigest object that implements the specified digest
  91. * algorithm. If the default provider package
  92. * provides an implementation of the requested digest algorithm,
  93. * an instance of MessageDigest containing that implementation is returned.
  94. * If the algorithm is not available in the default
  95. * package, other packages are searched.
  96. *
  97. * @param algorithm the name of the algorithm requested.
  98. * See Appendix A in the <a href=
  99. * "../../../guide/security/CryptoSpec.html#AppA">
  100. * Java Cryptography Architecture API Specification & Reference </a>
  101. * for information about standard algorithm names.
  102. *
  103. * @return a Message Digest object implementing the specified
  104. * algorithm.
  105. *
  106. * @exception NoSuchAlgorithmException if the algorithm is
  107. * not available in the caller's environment.
  108. */
  109. public static MessageDigest getInstance(String algorithm)
  110. throws NoSuchAlgorithmException {
  111. try {
  112. Object[] objs = Security.getImpl(algorithm, "MessageDigest",
  113. (String)null);
  114. if (objs[0] instanceof MessageDigest) {
  115. MessageDigest md = (MessageDigest)objs[0];
  116. md.provider = (Provider)objs[1];
  117. return md;
  118. } else {
  119. MessageDigest delegate =
  120. new Delegate((MessageDigestSpi)objs[0], algorithm);
  121. delegate.provider = (Provider)objs[1];
  122. return delegate;
  123. }
  124. } catch(NoSuchProviderException e) {
  125. throw new NoSuchAlgorithmException(algorithm + " not found");
  126. }
  127. }
  128. /**
  129. * Generates a MessageDigest object implementing the specified
  130. * algorithm, as supplied from the specified provider, if such an
  131. * algorithm is available from the provider.
  132. *
  133. * @param algorithm the name of the algorithm requested.
  134. * See Appendix A in the <a href=
  135. * "../../../guide/security/CryptoSpec.html#AppA">
  136. * Java Cryptography Architecture API Specification & Reference </a>
  137. * for information about standard algorithm names.
  138. *
  139. * @param provider the name of the provider.
  140. *
  141. * @return a Message Digest object implementing the specified
  142. * algorithm.
  143. *
  144. * @exception NoSuchAlgorithmException if the algorithm is
  145. * not available in the package supplied by the requested
  146. * provider.
  147. *
  148. * @exception NoSuchProviderException if the provider is not
  149. * available in the environment.
  150. *
  151. * @exception IllegalArgumentException if the provider name is null
  152. * or empty.
  153. *
  154. * @see Provider
  155. */
  156. public static MessageDigest getInstance(String algorithm, String provider)
  157. throws NoSuchAlgorithmException, NoSuchProviderException
  158. {
  159. if (provider == null || provider.length() == 0)
  160. throw new IllegalArgumentException("missing provider");
  161. Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
  162. if (objs[0] instanceof MessageDigest) {
  163. MessageDigest md = (MessageDigest)objs[0];
  164. md.provider = (Provider)objs[1];
  165. return md;
  166. } else {
  167. MessageDigest delegate =
  168. new Delegate((MessageDigestSpi)objs[0], algorithm);
  169. delegate.provider = (Provider)objs[1];
  170. return delegate;
  171. }
  172. }
  173. /**
  174. * Generates a MessageDigest object implementing the specified
  175. * algorithm, as supplied from the specified provider, if such an
  176. * algorithm is available from the provider. Note: the
  177. * <code>provider</code> doesn't have to be registered.
  178. *
  179. * @param algorithm the name of the algorithm requested.
  180. * See Appendix A in the <a href=
  181. * "../../../guide/security/CryptoSpec.html#AppA">
  182. * Java Cryptography Architecture API Specification & Reference </a>
  183. * for information about standard algorithm names.
  184. *
  185. * @param provider the provider.
  186. *
  187. * @return a Message Digest object implementing the specified
  188. * algorithm.
  189. *
  190. * @exception NoSuchAlgorithmException if the algorithm is
  191. * not available in the package supplied by the requested
  192. * provider.
  193. *
  194. * @exception IllegalArgumentException if the <code>provider</code> is
  195. * null.
  196. *
  197. * @see Provider
  198. *
  199. * @since 1.4
  200. */
  201. public static MessageDigest getInstance(String algorithm,
  202. Provider provider)
  203. throws NoSuchAlgorithmException
  204. {
  205. if (provider == null)
  206. throw new IllegalArgumentException("missing provider");
  207. Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
  208. if (objs[0] instanceof MessageDigest) {
  209. MessageDigest md = (MessageDigest)objs[0];
  210. md.provider = (Provider)objs[1];
  211. return md;
  212. } else {
  213. MessageDigest delegate =
  214. new Delegate((MessageDigestSpi)objs[0], algorithm);
  215. delegate.provider = (Provider)objs[1];
  216. return delegate;
  217. }
  218. }
  219. /**
  220. * Returns the provider of this message digest object.
  221. *
  222. * @return the provider of this message digest object
  223. */
  224. public final Provider getProvider() {
  225. return this.provider;
  226. }
  227. /**
  228. * Updates the digest using the specified byte.
  229. *
  230. * @param input the byte with which to update the digest.
  231. */
  232. public void update(byte input) {
  233. engineUpdate(input);
  234. state = IN_PROGRESS;
  235. }
  236. /**
  237. * Updates the digest using the specified array of bytes, starting
  238. * at the specified offset.
  239. *
  240. * @param input the array of bytes.
  241. *
  242. * @param offset the offset to start from in the array of bytes.
  243. *
  244. * @param len the number of bytes to use, starting at
  245. * <code>offset</code>.
  246. */
  247. public void update(byte[] input, int offset, int len) {
  248. if (input == null) {
  249. throw new IllegalArgumentException("No input buffer given");
  250. }
  251. if (input.length - offset < len) {
  252. throw new IllegalArgumentException("Input buffer too short");
  253. }
  254. engineUpdate(input, offset, len);
  255. state = IN_PROGRESS;
  256. }
  257. /**
  258. * Updates the digest using the specified array of bytes.
  259. *
  260. * @param input the array of bytes.
  261. */
  262. public void update(byte[] input) {
  263. engineUpdate(input, 0, input.length);
  264. state = IN_PROGRESS;
  265. }
  266. /**
  267. * Update the digest using the specified ByteBuffer. The digest is
  268. * updated using the <code>input.remaining()</code> bytes starting
  269. * at <code>input.position()</code>.
  270. * Upon return, the buffer's position will be equal to its limit;
  271. * its limit will not have changed.
  272. *
  273. * @param input the ByteBuffer
  274. * @since 1.5
  275. */
  276. public final void update(ByteBuffer input) {
  277. if (input == null) {
  278. throw new NullPointerException();
  279. }
  280. engineUpdate(input);
  281. state = IN_PROGRESS;
  282. }
  283. /**
  284. * Completes the hash computation by performing final operations
  285. * such as padding. The digest is reset after this call is made.
  286. *
  287. * @return the array of bytes for the resulting hash value.
  288. */
  289. public byte[] digest() {
  290. /* Resetting is the responsibility of implementors. */
  291. byte[] result = engineDigest();
  292. state = INITIAL;
  293. return result;
  294. }
  295. /**
  296. * Completes the hash computation by performing final operations
  297. * such as padding. The digest is reset after this call is made.
  298. *
  299. * @param buf output buffer for the computed digest
  300. *
  301. * @param offset offset into the output buffer to begin storing the digest
  302. *
  303. * @param len number of bytes within buf allotted for the digest
  304. *
  305. * @return the number of bytes placed into <code>buf</code>
  306. *
  307. * @exception DigestException if an error occurs.
  308. */
  309. public int digest(byte[] buf, int offset, int len) throws DigestException {
  310. if (buf == null) {
  311. throw new IllegalArgumentException("No output buffer given");
  312. }
  313. if (buf.length - offset < len) {
  314. throw new IllegalArgumentException
  315. ("Output buffer too small for specified offset and length");
  316. }
  317. int numBytes = engineDigest(buf, offset, len);
  318. state = INITIAL;
  319. return numBytes;
  320. }
  321. /**
  322. * Performs a final update on the digest using the specified array
  323. * of bytes, then completes the digest computation. That is, this
  324. * method first calls {@link #update(byte[]) update(input)},
  325. * passing the <i>input</i> array to the <code>update</code> method,
  326. * then calls {@link #digest() digest()}.
  327. *
  328. * @param input the input to be updated before the digest is
  329. * completed.
  330. *
  331. * @return the array of bytes for the resulting hash value.
  332. */
  333. public byte[] digest(byte[] input) {
  334. update(input);
  335. return digest();
  336. }
  337. /**
  338. * Returns a string representation of this message digest object.
  339. */
  340. public String toString() {
  341. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  342. PrintStream p = new PrintStream(baos);
  343. p.print(algorithm+" Message Digest from "+provider.getName()+", ");
  344. switch (state) {
  345. case INITIAL:
  346. p.print("<initialized>");
  347. break;
  348. case IN_PROGRESS:
  349. p.print("<in progress>");
  350. break;
  351. }
  352. p.println();
  353. return (baos.toString());
  354. }
  355. /**
  356. * Compares two digests for equality. Does a simple byte compare.
  357. *
  358. * @param digesta one of the digests to compare.
  359. *
  360. * @param digestb the other digest to compare.
  361. *
  362. * @return true if the digests are equal, false otherwise.
  363. */
  364. public static boolean isEqual(byte digesta[], byte digestb[]) {
  365. if (digesta.length != digestb.length)
  366. return false;
  367. for (int i = 0; i < digesta.length; i++) {
  368. if (digesta[i] != digestb[i]) {
  369. return false;
  370. }
  371. }
  372. return true;
  373. }
  374. /**
  375. * Resets the digest for further use.
  376. */
  377. public void reset() {
  378. engineReset();
  379. state = INITIAL;
  380. }
  381. /**
  382. * Returns a string that identifies the algorithm, independent of
  383. * implementation details. The name should be a standard
  384. * Java Security name (such as "SHA", "MD5", and so on).
  385. * See Appendix A in the <a href=
  386. * "../../../guide/security/CryptoSpec.html#AppA">
  387. * Java Cryptography Architecture API Specification & Reference </a>
  388. * for information about standard algorithm names.
  389. *
  390. * @return the name of the algorithm
  391. */
  392. public final String getAlgorithm() {
  393. return this.algorithm;
  394. }
  395. /**
  396. * Returns the length of the digest in bytes, or 0 if this operation is
  397. * not supported by the provider and the implementation is not cloneable.
  398. *
  399. * @return the digest length in bytes, or 0 if this operation is not
  400. * supported by the provider and the implementation is not cloneable.
  401. *
  402. * @since 1.2
  403. */
  404. public final int getDigestLength() {
  405. int digestLen = engineGetDigestLength();
  406. if (digestLen == 0) {
  407. try {
  408. MessageDigest md = (MessageDigest)clone();
  409. byte[] digest = md.digest();
  410. return digest.length;
  411. } catch (CloneNotSupportedException e) {
  412. return digestLen;
  413. }
  414. }
  415. return digestLen;
  416. }
  417. /**
  418. * Returns a clone if the implementation is cloneable.
  419. *
  420. * @return a clone if the implementation is cloneable.
  421. *
  422. * @exception CloneNotSupportedException if this is called on an
  423. * implementation that does not support <code>Cloneable</code>.
  424. */
  425. public Object clone() throws CloneNotSupportedException {
  426. if (this instanceof Cloneable) {
  427. return super.clone();
  428. } else {
  429. throw new CloneNotSupportedException();
  430. }
  431. }
  432. /*
  433. * The following class allows providers to extend from MessageDigestSpi
  434. * rather than from MessageDigest. It represents a MessageDigest with an
  435. * encapsulated, provider-supplied SPI object (of type MessageDigestSpi).
  436. * If the provider implementation is an instance of MessageDigestSpi,
  437. * the getInstance() methods above return an instance of this class, with
  438. * the SPI object encapsulated.
  439. *
  440. * Note: All SPI methods from the original MessageDigest class have been
  441. * moved up the hierarchy into a new class (MessageDigestSpi), which has
  442. * been interposed in the hierarchy between the API (MessageDigest)
  443. * and its original parent (Object).
  444. */
  445. static class Delegate extends MessageDigest {
  446. // The provider implementation (delegate)
  447. private MessageDigestSpi digestSpi;
  448. // constructor
  449. public Delegate(MessageDigestSpi digestSpi, String algorithm) {
  450. super(algorithm);
  451. this.digestSpi = digestSpi;
  452. }
  453. /*
  454. * Returns a clone if the delegate is cloneable.
  455. *
  456. * @return a clone if the delegate is cloneable.
  457. *
  458. * @exception CloneNotSupportedException if this is called on a
  459. * delegate that does not support <code>Cloneable</code>.
  460. */
  461. public Object clone() throws CloneNotSupportedException {
  462. if (digestSpi instanceof Cloneable) {
  463. MessageDigestSpi digestSpiClone =
  464. (MessageDigestSpi)digestSpi.clone();
  465. // Because 'algorithm', 'provider', and 'state' are private
  466. // members of our supertype, we must perform a cast to
  467. // access them.
  468. MessageDigest that =
  469. new Delegate(digestSpiClone,
  470. ((MessageDigest)this).algorithm);
  471. that.provider = ((MessageDigest)this).provider;
  472. that.state = ((MessageDigest)this).state;
  473. return that;
  474. } else {
  475. throw new CloneNotSupportedException();
  476. }
  477. }
  478. protected int engineGetDigestLength() {
  479. return digestSpi.engineGetDigestLength();
  480. }
  481. protected void engineUpdate(byte input) {
  482. digestSpi.engineUpdate(input);
  483. }
  484. protected void engineUpdate(byte[] input, int offset, int len) {
  485. digestSpi.engineUpdate(input, offset, len);
  486. }
  487. protected void engineUpdate(ByteBuffer input) {
  488. digestSpi.engineUpdate(input);
  489. }
  490. protected byte[] engineDigest() {
  491. return digestSpi.engineDigest();
  492. }
  493. protected int engineDigest(byte[] buf, int offset, int len)
  494. throws DigestException {
  495. return digestSpi.engineDigest(buf, offset, len);
  496. }
  497. protected void engineReset() {
  498. digestSpi.engineReset();
  499. }
  500. }
  501. }