MessageDigest.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /* MessageDigest.java --- The message digest interface.
  2. Copyright (C) 1999, 2002 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., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 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. public abstract class MessageDigest extends MessageDigestSpi
  33. {
  34. private String algorithm;
  35. Provider provider;
  36. private byte[] lastDigest;
  37. /**
  38. Creates a MessageDigest representing the specified
  39. algorithm.
  40. @param algorithm the name of digest algorithm to choose
  41. */
  42. protected MessageDigest(String algorithm)
  43. {
  44. this.algorithm = algorithm;
  45. provider = null;
  46. }
  47. /**
  48. Gets an instance of the MessageDigest class representing
  49. the specified digest. If the algorithm is not found then,
  50. it throws NoSuchAlgorithmException.
  51. @param algorithm the name of digest algorithm to choose
  52. @return a MessageDigest representing the desired algorithm
  53. @exception NoSuchAlgorithmException if the algorithm is not implemented by
  54. providers
  55. */
  56. public static MessageDigest getInstance(String algorithm)
  57. throws NoSuchAlgorithmException
  58. {
  59. Provider[] p = Security.getProviders();
  60. for (int i = 0; i < p.length; i++)
  61. {
  62. try
  63. {
  64. return getInstance(algorithm, p[i]);
  65. }
  66. catch (NoSuchAlgorithmException ignored) {}
  67. }
  68. throw new NoSuchAlgorithmException(algorithm);
  69. }
  70. /**
  71. Gets an instance of the MessageDigest class representing
  72. the specified digest from the specified provider. If the
  73. algorithm is not found then, it throws NoSuchAlgorithmException.
  74. If the provider is not found, then it throws
  75. NoSuchProviderException.
  76. @param algorithm the name of digest algorithm to choose
  77. @param provider the name of the provider to find the algorithm in
  78. @return a MessageDigest representing the desired algorithm
  79. @exception NoSuchAlgorithmException if the algorithm is not implemented by
  80. the provider
  81. @exception NoSuchProviderException if the provider is not found
  82. */
  83. public static MessageDigest getInstance(String algorithm, String provider)
  84. throws NoSuchAlgorithmException, NoSuchProviderException
  85. {
  86. Provider p = Security.getProvider(provider);
  87. if (p == null)
  88. throw new NoSuchProviderException(provider);
  89. return getInstance(algorithm, p);
  90. }
  91. private static MessageDigest getInstance(String algorithm, Provider p)
  92. throws NoSuchAlgorithmException
  93. {
  94. // try the name as is
  95. String className = p.getProperty("MessageDigest." + algorithm);
  96. if (className == null) { // try all uppercase
  97. String upper = algorithm.toUpperCase();
  98. className = p.getProperty("MessageDigest." + upper);
  99. if (className == null) { // try if it's an alias
  100. String alias = p.getProperty("Alg.Alias.MessageDigest." +algorithm);
  101. if (alias == null) { // try all-uppercase alias name
  102. alias = p.getProperty("Alg.Alias.MessageDigest." +upper);
  103. if (alias == null) { // spit the dummy
  104. throw new NoSuchAlgorithmException(algorithm);
  105. }
  106. }
  107. className = p.getProperty("MessageDigest." + alias);
  108. if (className == null) {
  109. throw new NoSuchAlgorithmException(algorithm);
  110. }
  111. }
  112. }
  113. return getInstance(className, algorithm, p);
  114. }
  115. private static MessageDigest getInstance(String classname,
  116. String algorithm,
  117. Provider provider)
  118. throws NoSuchAlgorithmException
  119. {
  120. if (classname == null)
  121. throw new NoSuchAlgorithmException(algorithm);
  122. MessageDigest result = null;
  123. try
  124. {
  125. Object obj = Class.forName(classname).newInstance();
  126. if (obj instanceof MessageDigest) {
  127. result = (MessageDigest) obj;
  128. result.algorithm = algorithm;
  129. } else if (obj instanceof MessageDigestSpi) {
  130. result = new DummyMessageDigest((MessageDigestSpi) obj, algorithm);
  131. } else {
  132. throw new ClassCastException("Class "+classname+" from Provider "
  133. +provider.getName()
  134. +" does not extend java.security.MessageDigestSpi");
  135. }
  136. result.provider = provider;
  137. return result;
  138. }
  139. catch (ClassNotFoundException cnfe)
  140. {
  141. throw new NoSuchAlgorithmException(algorithm + ": Class not found.");
  142. }
  143. catch (InstantiationException ie)
  144. {
  145. throw new NoSuchAlgorithmException(algorithm
  146. + ": Class instantiation failed.");
  147. }
  148. catch (IllegalAccessException iae)
  149. {
  150. throw new NoSuchAlgorithmException(algorithm + ": Illegal Access");
  151. }
  152. }
  153. /**
  154. Gets the provider that the MessageDigest is from.
  155. @return the provider the this MessageDigest
  156. */
  157. public final Provider getProvider()
  158. {
  159. return provider;
  160. }
  161. /**
  162. Updates the digest with the byte.
  163. @param input byte to update the digest with
  164. */
  165. public void update(byte input)
  166. {
  167. engineUpdate(input);
  168. }
  169. /**
  170. Updates the digest with the bytes from the array from the
  171. specified offset to the specified length.
  172. @param input bytes to update the digest with
  173. @param offset the offset to start at
  174. @param len length of the data to update with
  175. */
  176. public void update(byte[]input, int offset, int len)
  177. {
  178. engineUpdate(input, offset, len);
  179. }
  180. /**
  181. Updates the digest with the bytes from the array.
  182. @param input bytes to update the digest with
  183. */
  184. public void update(byte[]input)
  185. {
  186. engineUpdate(input, 0, input.length);
  187. }
  188. /**
  189. Computes the digest of the stored data.
  190. @return a byte array representing the message digest
  191. */
  192. public byte[] digest()
  193. {
  194. return lastDigest = engineDigest();
  195. }
  196. /**
  197. Computes the final digest of the stored bytes and returns
  198. them.
  199. @param buf An array of bytes to store the digest
  200. @param offset An offset to start storing the digest at
  201. @param len The length of the buffer
  202. @return Returns the length of the buffer
  203. */
  204. public int digest(byte[]buf, int offset, int len) throws DigestException
  205. {
  206. return engineDigest(buf, offset, len);
  207. }
  208. /**
  209. Computes a final update using the input array of bytes,
  210. then computes a final digest and returns it. It calls
  211. update(input) and then digest();
  212. @param input An array of bytes to perform final update with
  213. @return a byte array representing the message digest
  214. */
  215. public byte[] digest(byte[]input)
  216. {
  217. update(input);
  218. return digest();
  219. }
  220. /**
  221. Returns a representation of the MessageDigest as a String.
  222. @return a string representing the message digest
  223. */
  224. public String toString()
  225. {
  226. return (getClass()).getName()
  227. + " Message Digest <" + digestToString() + ">";
  228. }
  229. /**
  230. Does a simple byte comparison of the two digests.
  231. @param digesta first digest to compare
  232. @param digestb second digest to compare
  233. @return true if they are equal, false otherwise
  234. */
  235. public static boolean isEqual(byte[]digesta, byte[]digestb)
  236. {
  237. if (digesta.length != digestb.length)
  238. return false;
  239. for (int i = digesta.length - 1; i >= 0; --i)
  240. if (digesta[i] != digestb[i])
  241. return false;
  242. return true;
  243. }
  244. /**
  245. Resets the message digest.
  246. */
  247. public void reset()
  248. {
  249. engineReset();
  250. }
  251. /**
  252. Gets the name of the algorithm currently used.
  253. The names of algorithms are usually SHA-1 or MD5.
  254. @return name of algorithm.
  255. */
  256. public final String getAlgorithm()
  257. {
  258. return algorithm;
  259. }
  260. /**
  261. Gets the length of the message digest.
  262. The default is zero which means that this message digest
  263. does not implement this function.
  264. @return length of the message digest
  265. */
  266. public final int getDigestLength()
  267. {
  268. return engineGetDigestLength();
  269. }
  270. /**
  271. Returns a clone of this class if supported.
  272. If it does not then it throws CloneNotSupportedException.
  273. The cloning of this class depends on whether the subclass
  274. MessageDigestSpi implements Cloneable which contains the
  275. actual implementation of the appropriate algorithm.
  276. @return clone of this class
  277. @exception CloneNotSupportedException this class does not support cloning
  278. */
  279. public Object clone() throws CloneNotSupportedException
  280. {
  281. if (this instanceof Cloneable)
  282. return super.clone();
  283. else
  284. throw new CloneNotSupportedException();
  285. }
  286. private String digestToString()
  287. {
  288. byte[] digest = lastDigest;
  289. if (digest == null)
  290. return "incomplete";
  291. StringBuffer buf = new StringBuffer();
  292. int len = digest.length;
  293. for (int i = 0; i < len; ++i)
  294. {
  295. byte b = digest[i];
  296. byte high = (byte) ((b & 0xff) >>> 4);
  297. byte low = (byte) (b & 0xf);
  298. buf.append(high > 9 ? ('a' - 10) + high : '0' + high);
  299. buf.append(low > 9 ? ('a' - 10) + low : '0' + low);
  300. }
  301. return buf.toString();
  302. }
  303. }