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