MessageDigest.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /* MessageDigest.java --- The message digest interface.
  2. Copyright (C) 1999, 2002, 2003, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.security;
  32. import gnu.java.lang.CPStringBuilder;
  33. import gnu.java.security.Engine;
  34. import java.nio.ByteBuffer;
  35. import java.lang.reflect.InvocationTargetException;
  36. /**
  37. * Message digests are secure one-way hash functions that take arbitrary-sized
  38. * data and output a fixed-length hash value.
  39. *
  40. * @see MessageDigestSpi
  41. * @since JDK 1.1
  42. */
  43. public abstract class MessageDigest extends MessageDigestSpi
  44. {
  45. /** The service name for message digests. */
  46. private static final String MESSAGE_DIGEST = "MessageDigest";
  47. private String algorithm;
  48. Provider provider;
  49. private byte[] lastDigest;
  50. /**
  51. * Constructs a new instance of <code>MessageDigest</code> representing the
  52. * specified algorithm.
  53. *
  54. * @param algorithm
  55. * the name of the digest algorithm to use.
  56. */
  57. protected MessageDigest(String algorithm)
  58. {
  59. this.algorithm = algorithm;
  60. provider = null;
  61. }
  62. /**
  63. * Returns a new instance of <code>MessageDigest</code> representing the
  64. * specified algorithm.
  65. *
  66. * @param algorithm the name of the digest algorithm to use.
  67. * @return a new instance representing the desired algorithm.
  68. * @throws NoSuchAlgorithmException if the algorithm is not implemented by any
  69. * provider.
  70. * @throws IllegalArgumentException if <code>algorithm</code> is
  71. * <code>null</code> or is an empty string.
  72. */
  73. public static MessageDigest getInstance(String algorithm)
  74. throws NoSuchAlgorithmException
  75. {
  76. Provider[] p = Security.getProviders();
  77. NoSuchAlgorithmException lastException = null;
  78. for (int i = 0; i < p.length; i++)
  79. try
  80. {
  81. return getInstance(algorithm, p[i]);
  82. }
  83. catch (NoSuchAlgorithmException x)
  84. {
  85. lastException = x;
  86. }
  87. if (lastException != null)
  88. throw lastException;
  89. throw new NoSuchAlgorithmException(algorithm);
  90. }
  91. /**
  92. * Returns a new instance of <code>MessageDigest</code> representing the
  93. * specified algorithm from a named provider.
  94. *
  95. * @param algorithm the name of the digest algorithm to use.
  96. * @param provider the name of the provider to use.
  97. * @return a new instance representing the desired algorithm.
  98. * @throws NoSuchAlgorithmException if the algorithm is not implemented by the
  99. * named provider.
  100. * @throws NoSuchProviderException if the named provider was not found.
  101. * @throws IllegalArgumentException if either <code>algorithm</code> or
  102. * <code>provider</code> is <code>null</code> or empty.
  103. */
  104. public static MessageDigest getInstance(String algorithm, String provider)
  105. throws NoSuchAlgorithmException, NoSuchProviderException
  106. {
  107. if (provider == null)
  108. throw new IllegalArgumentException("provider MUST NOT be null");
  109. provider = provider.trim();
  110. if (provider.length() == 0)
  111. throw new IllegalArgumentException("provider MUST NOT be empty");
  112. Provider p = Security.getProvider(provider);
  113. if (p == null)
  114. throw new NoSuchProviderException(provider);
  115. return getInstance(algorithm, p);
  116. }
  117. /**
  118. * Returns a new instance of <code>MessageDigest</code> representing the
  119. * specified algorithm from a designated {@link Provider}.
  120. *
  121. * @param algorithm the name of the digest algorithm to use.
  122. * @param provider the {@link Provider} to use.
  123. * @return a new instance representing the desired algorithm.
  124. * @throws NoSuchAlgorithmException if the algorithm is not implemented by
  125. * {@link Provider}.
  126. * @throws IllegalArgumentException if either <code>algorithm</code> or
  127. * <code>provider</code> is <code>null</code>, or if
  128. * <code>algorithm</code> is an empty string.
  129. * @since 1.4
  130. * @see Provider
  131. */
  132. public static MessageDigest getInstance(String algorithm, Provider provider)
  133. throws NoSuchAlgorithmException
  134. {
  135. CPStringBuilder sb = new CPStringBuilder("MessageDigest for algorithm [")
  136. .append(algorithm).append("] from provider[")
  137. .append(provider).append("] ");
  138. Object o;
  139. try
  140. {
  141. o = Engine.getInstance(MESSAGE_DIGEST, algorithm, provider);
  142. }
  143. catch (InvocationTargetException x)
  144. {
  145. Throwable cause = x.getCause();
  146. if (cause instanceof NoSuchAlgorithmException)
  147. throw (NoSuchAlgorithmException) cause;
  148. if (cause == null)
  149. cause = x;
  150. sb.append("could not be created");
  151. NoSuchAlgorithmException y = new NoSuchAlgorithmException(sb.toString());
  152. y.initCause(cause);
  153. throw y;
  154. }
  155. MessageDigest result;
  156. if (o instanceof MessageDigestSpi)
  157. result = new DummyMessageDigest((MessageDigestSpi) o, algorithm);
  158. else if (o instanceof MessageDigest)
  159. {
  160. result = (MessageDigest) o;
  161. result.algorithm = algorithm;
  162. }
  163. else
  164. {
  165. sb.append("is of an unexpected Type: ").append(o.getClass().getName());
  166. throw new NoSuchAlgorithmException(sb.toString());
  167. }
  168. result.provider = provider;
  169. return result;
  170. }
  171. /**
  172. * Returns the {@link Provider} of this instance.
  173. *
  174. * @return the {@link Provider} of this instance.
  175. */
  176. public final Provider getProvider()
  177. {
  178. return provider;
  179. }
  180. /**
  181. * Updates the digest with the byte.
  182. *
  183. * @param input byte to update the digest with.
  184. */
  185. public void update(byte input)
  186. {
  187. engineUpdate(input);
  188. }
  189. /**
  190. * Updates the digest with the bytes from the array starting from the
  191. * specified offset and using the specified length of bytes.
  192. *
  193. * @param input
  194. * bytes to update the digest with.
  195. * @param offset
  196. * the offset to start at.
  197. * @param len
  198. * length of the data to update with.
  199. */
  200. public void update(byte[] input, int offset, int len)
  201. {
  202. engineUpdate(input, offset, len);
  203. }
  204. /**
  205. * Updates the digest with the bytes of an array.
  206. *
  207. * @param input bytes to update the digest with.
  208. */
  209. public void update(byte[] input)
  210. {
  211. engineUpdate(input, 0, input.length);
  212. }
  213. /**
  214. * Updates the digest with the remaining bytes of a buffer.
  215. *
  216. * @param input The input byte buffer.
  217. * @since 1.5
  218. */
  219. public final void update (ByteBuffer input)
  220. {
  221. engineUpdate (input);
  222. }
  223. /**
  224. * Computes the final digest of the stored data.
  225. *
  226. * @return a byte array representing the message digest.
  227. */
  228. public byte[] digest()
  229. {
  230. return lastDigest = engineDigest();
  231. }
  232. /**
  233. * Computes the final digest of the stored bytes and returns the result.
  234. *
  235. * @param buf
  236. * an array of bytes to store the result in.
  237. * @param offset
  238. * an offset to start storing the result at.
  239. * @param len
  240. * the length of the buffer.
  241. * @return Returns the length of the buffer.
  242. */
  243. public int digest(byte[] buf, int offset, int len) throws DigestException
  244. {
  245. return engineDigest(buf, offset, len);
  246. }
  247. /**
  248. * Computes a final update using the input array of bytes, then computes a
  249. * final digest and returns it. It calls {@link #update(byte[])} and then
  250. * {@link #digest(byte[])}.
  251. *
  252. * @param input
  253. * an array of bytes to perform final update with.
  254. * @return a byte array representing the message digest.
  255. */
  256. public byte[] digest(byte[] input)
  257. {
  258. update(input);
  259. return digest();
  260. }
  261. /**
  262. * Returns a string representation of this instance.
  263. *
  264. * @return a string representation of this instance.
  265. */
  266. public String toString()
  267. {
  268. return (getClass()).getName() + " Message Digest <" + digestToString() + ">";
  269. }
  270. /**
  271. * Does a simple byte comparison of the two digests.
  272. *
  273. * @param digesta
  274. * first digest to compare.
  275. * @param digestb
  276. * second digest to compare.
  277. * @return <code>true</code> if both are equal, <code>false</code>
  278. * otherwise.
  279. */
  280. public static boolean isEqual(byte[] digesta, byte[] digestb)
  281. {
  282. if (digesta.length != digestb.length)
  283. return false;
  284. for (int i = digesta.length - 1; i >= 0; --i)
  285. if (digesta[i] != digestb[i])
  286. return false;
  287. return true;
  288. }
  289. /** Resets this instance. */
  290. public void reset()
  291. {
  292. engineReset();
  293. }
  294. /**
  295. * Returns the name of message digest algorithm.
  296. *
  297. * @return the name of message digest algorithm.
  298. */
  299. public final String getAlgorithm()
  300. {
  301. return algorithm;
  302. }
  303. /**
  304. * Returns the length of the message digest. The default is zero which means
  305. * that the concrete implementation does not implement this method.
  306. *
  307. * @return length of the message digest.
  308. * @since 1.2
  309. */
  310. public final int getDigestLength()
  311. {
  312. return engineGetDigestLength();
  313. }
  314. /**
  315. * Returns a clone of this instance if cloning is supported. If it does not
  316. * then a {@link CloneNotSupportedException} is thrown. Cloning depends on
  317. * whether the subclass {@link MessageDigestSpi} implements {@link Cloneable}
  318. * which contains the actual implementation of the appropriate algorithm.
  319. *
  320. * @return a clone of this instance.
  321. * @throws CloneNotSupportedException
  322. * the implementation does not support cloning.
  323. */
  324. public Object clone() throws CloneNotSupportedException
  325. {
  326. return super.clone();
  327. }
  328. private String digestToString()
  329. {
  330. byte[] digest = lastDigest;
  331. if (digest == null)
  332. return "incomplete";
  333. CPStringBuilder buf = new CPStringBuilder();
  334. int len = digest.length;
  335. for (int i = 0; i < len; ++i)
  336. {
  337. byte b = digest[i];
  338. byte high = (byte) ((b & 0xff) >>> 4);
  339. byte low = (byte) (b & 0xf);
  340. buf.append(high > 9 ? ('a' - 10) + high : '0' + high);
  341. buf.append(low > 9 ? ('a' - 10) + low : '0' + low);
  342. }
  343. return buf.toString();
  344. }
  345. }