Mac.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /* Mac.java -- The message authentication code interface.
  2. Copyright (C) 2004 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 javax.crypto;
  32. import gnu.java.security.Engine;
  33. import java.lang.reflect.InvocationTargetException;
  34. import java.nio.ByteBuffer;
  35. import java.security.InvalidAlgorithmParameterException;
  36. import java.security.InvalidKeyException;
  37. import java.security.Key;
  38. import java.security.NoSuchAlgorithmException;
  39. import java.security.NoSuchProviderException;
  40. import java.security.Provider;
  41. import java.security.Security;
  42. import java.security.spec.AlgorithmParameterSpec;
  43. /**
  44. * This class implements a "message authentication code" (MAC), a method
  45. * to ensure the integrity of data transmitted between two parties who
  46. * share a common secret key.
  47. *
  48. * <p>The best way to describe a MAC is as a <i>keyed one-way hash
  49. * function</i>, which looks like:
  50. *
  51. * <blockquote><p><code>D = MAC(K, M)</code></blockquote>
  52. *
  53. * <p>where <code>K</code> is the key, <code>M</code> is the message,
  54. * and <code>D</code> is the resulting digest. One party will usually
  55. * send the concatenation <code>M || D</code> to the other party, who
  56. * will then verify <code>D</code> by computing <code>D'</code> in a
  57. * similar fashion. If <code>D == D'</code>, then the message is assumed
  58. * to be authentic.
  59. *
  60. * @author Casey Marshall (csm@gnu.org)
  61. */
  62. public class Mac implements Cloneable
  63. {
  64. // Fields.
  65. // ------------------------------------------------------------------------
  66. private static final String SERVICE = "Mac";
  67. /** The underlying MAC implementation. */
  68. private MacSpi macSpi;
  69. /** The provider we got our implementation from. */
  70. private Provider provider;
  71. /** The name of the algorithm. */
  72. private String algorithm;
  73. /** Whether or not we've been initialized. */
  74. private boolean virgin;
  75. // Constructor.
  76. // ------------------------------------------------------------------------
  77. /**
  78. * Creates a new Mac instance.
  79. *
  80. * @param macSpi The underlying MAC implementation.
  81. * @param provider The provider of this implementation.
  82. * @param algorithm The name of this MAC algorithm.
  83. */
  84. protected Mac(MacSpi macSpi, Provider provider, String algorithm)
  85. {
  86. this.macSpi = macSpi;
  87. this.provider = provider;
  88. this.algorithm = algorithm;
  89. virgin = true;
  90. }
  91. /**
  92. * Create an instance of the named algorithm from the first provider with an
  93. * appropriate implementation.
  94. *
  95. * @param algorithm The name of the algorithm.
  96. * @return An appropriate Mac instance, if the specified algorithm is
  97. * implemented by a provider.
  98. * @throws NoSuchAlgorithmException If no implementation of the named
  99. * algorithm is installed.
  100. * @throws IllegalArgumentException if <code>algorithm</code> is
  101. * <code>null</code> or is an empty string.
  102. */
  103. public static final Mac getInstance(String algorithm)
  104. throws NoSuchAlgorithmException
  105. {
  106. Provider[] p = Security.getProviders();
  107. NoSuchAlgorithmException lastException = null;
  108. for (int i = 0; i < p.length; i++)
  109. try
  110. {
  111. return getInstance(algorithm, p[i]);
  112. }
  113. catch (NoSuchAlgorithmException x)
  114. {
  115. lastException = x;
  116. }
  117. if (lastException != null)
  118. throw lastException;
  119. throw new NoSuchAlgorithmException(algorithm);
  120. }
  121. /**
  122. * Create an instance of the named algorithm from the named provider.
  123. *
  124. * @param algorithm The name of the algorithm.
  125. * @param provider The name of the provider.
  126. * @return An appropriate Mac instance, if the specified algorithm is
  127. * implemented by the named provider.
  128. * @throws NoSuchAlgorithmException If the named provider has no
  129. * implementation of the algorithm.
  130. * @throws NoSuchProviderException If the named provider does not exist.
  131. * @throws IllegalArgumentException if either <code>algorithm</code> or
  132. * <code>provider</code> is <code>null</code>, or if
  133. * <code>algorithm</code> is an empty string.
  134. */
  135. public static final Mac getInstance(String algorithm, String provider)
  136. throws NoSuchAlgorithmException, NoSuchProviderException
  137. {
  138. if (provider == null)
  139. throw new IllegalArgumentException("provider MUST NOT be null");
  140. Provider p = Security.getProvider(provider);
  141. if (p == null)
  142. throw new NoSuchProviderException(provider);
  143. return getInstance(algorithm, p);
  144. }
  145. /**
  146. * Create an instance of the named algorithm from a provider.
  147. *
  148. * @param algorithm The name of the algorithm.
  149. * @param provider The provider.
  150. * @return An appropriate Mac instance, if the specified algorithm is
  151. * implemented by the provider.
  152. * @throws NoSuchAlgorithmException If the provider has no implementation of
  153. * the algorithm.
  154. * @throws IllegalArgumentException if either <code>algorithm</code> or
  155. * <code>provider</code> is <code>null</code>, or if
  156. * <code>algorithm</code> is an empty string.
  157. */
  158. public static final Mac getInstance(String algorithm, Provider provider)
  159. throws NoSuchAlgorithmException
  160. {
  161. StringBuilder sb = new StringBuilder("Mac algorithm [")
  162. .append(algorithm).append("] from provider[")
  163. .append(provider).append("] could not be created");
  164. Throwable cause;
  165. try
  166. {
  167. Object spi = Engine.getInstance(SERVICE, algorithm, provider);
  168. return new Mac((MacSpi) spi, provider, algorithm);
  169. }
  170. catch (InvocationTargetException x)
  171. {
  172. cause = x.getCause();
  173. if (cause instanceof NoSuchAlgorithmException)
  174. throw (NoSuchAlgorithmException) cause;
  175. if (cause == null)
  176. cause = x;
  177. }
  178. catch (ClassCastException x)
  179. {
  180. cause = x;
  181. }
  182. NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString());
  183. x.initCause(cause);
  184. throw x;
  185. }
  186. /**
  187. * Finishes the computation of a MAC and returns the digest.
  188. *
  189. * <p>After this method succeeds, it may be used again as just after a
  190. * call to <code>init</code>, and can compute another MAC using the
  191. * same key and parameters.
  192. *
  193. * @return The message authentication code.
  194. * @throws java.lang.IllegalStateException If this instnace has not
  195. * been initialized.
  196. */
  197. public final byte[] doFinal() throws IllegalStateException
  198. {
  199. if (virgin)
  200. {
  201. throw new IllegalStateException("not initialized");
  202. }
  203. byte[] digest = macSpi.engineDoFinal();
  204. reset();
  205. return digest;
  206. }
  207. /**
  208. * Finishes the computation of a MAC with a final byte array (or
  209. * computes a MAC over those bytes only) and returns the digest.
  210. *
  211. * <p>After this method succeeds, it may be used again as just after a
  212. * call to <code>init</code>, and can compute another MAC using the
  213. * same key and parameters.
  214. *
  215. * @param input The bytes to add.
  216. * @return The message authentication code.
  217. * @throws java.lang.IllegalStateException If this instnace has not
  218. * been initialized.
  219. */
  220. public final byte[] doFinal(byte[] input) throws IllegalStateException
  221. {
  222. update(input);
  223. byte[] digest = macSpi.engineDoFinal();
  224. reset();
  225. return digest;
  226. }
  227. /**
  228. * Finishes the computation of a MAC and places the result into the
  229. * given array.
  230. *
  231. * <p>After this method succeeds, it may be used again as just after a
  232. * call to <code>init</code>, and can compute another MAC using the
  233. * same key and parameters.
  234. *
  235. * @param output The destination for the result.
  236. * @param outOffset The index in the output array to start.
  237. * @return The message authentication code.
  238. * @throws java.lang.IllegalStateException If this instnace has not
  239. * been initialized.
  240. * @throws javax.crypto.ShortBufferException If <code>output</code> is
  241. * not large enough to hold the result.
  242. */
  243. public final void doFinal(byte[] output, int outOffset)
  244. throws IllegalStateException, ShortBufferException
  245. {
  246. if (virgin)
  247. {
  248. throw new IllegalStateException("not initialized");
  249. }
  250. if (output.length - outOffset < getMacLength())
  251. {
  252. throw new ShortBufferException();
  253. }
  254. byte[] mac = macSpi.engineDoFinal();
  255. System.arraycopy(mac, 0, output, outOffset, getMacLength());
  256. reset();
  257. }
  258. /**
  259. * Returns the name of this MAC algorithm.
  260. *
  261. * @return The MAC name.
  262. */
  263. public final String getAlgorithm()
  264. {
  265. return algorithm;
  266. }
  267. /**
  268. * Get the size of the MAC. This is the size of the array returned by
  269. * {@link #doFinal()} and {@link #doFinal(byte[])}, and the minimum
  270. * number of bytes that must be available in the byte array passed to
  271. * {@link #doFinal(byte[],int)}.
  272. *
  273. * @return The MAC length.
  274. */
  275. public final int getMacLength()
  276. {
  277. return macSpi.engineGetMacLength();
  278. }
  279. /**
  280. * Get the provider of the underlying implementation.
  281. *
  282. * @return The provider.
  283. */
  284. public final Provider getProvider()
  285. {
  286. return provider;
  287. }
  288. /**
  289. * Initialize this MAC with a key and no parameters.
  290. *
  291. * @param key The key to initialize this instance with.
  292. * @throws java.security.InvalidKeyException If the key is
  293. * unacceptable.
  294. */
  295. public final void init(Key key) throws InvalidKeyException
  296. {
  297. try
  298. {
  299. init(key, null);
  300. }
  301. catch (InvalidAlgorithmParameterException iape)
  302. {
  303. throw new IllegalArgumentException(algorithm + " needs parameters");
  304. }
  305. }
  306. /**
  307. * Initialize this MAC with a key and parameters.
  308. *
  309. * @param key The key to initialize this instance with.
  310. * @param params The algorithm-specific parameters.
  311. * @throws java.security.InvalidAlgorithmParameterException If the
  312. * algorithm parameters are unacceptable.
  313. * @throws java.security.InvalidKeyException If the key is
  314. * unacceptable.
  315. */
  316. public final void init(Key key, AlgorithmParameterSpec params)
  317. throws InvalidAlgorithmParameterException, InvalidKeyException
  318. {
  319. macSpi.engineInit(key, params);
  320. virgin = false; // w00t!
  321. }
  322. /**
  323. * Reset this instance. A call to this method returns this instance
  324. * back to the state it was in just after it was initialized.
  325. */
  326. public final void reset()
  327. {
  328. macSpi.engineReset();
  329. }
  330. /**
  331. * Update the computation with a single byte.
  332. *
  333. * @param input The next byte.
  334. * @throws java.lang.IllegalStateException If this instance has not
  335. * been initialized.
  336. */
  337. public final void update(byte input) throws IllegalStateException
  338. {
  339. if (virgin)
  340. {
  341. throw new IllegalStateException("not initialized");
  342. }
  343. macSpi.engineUpdate(input);
  344. }
  345. /**
  346. * Update the computation with a byte array.
  347. *
  348. * @param input The next bytes.
  349. * @throws java.lang.IllegalStateException If this instance has not
  350. * been initialized.
  351. */
  352. public final void update(byte[] input) throws IllegalStateException
  353. {
  354. update(input, 0, input.length);
  355. }
  356. /**
  357. * Update the computation with a portion of a byte array.
  358. *
  359. * @param input The next bytes.
  360. * @param offset The index in <code>input</code> to start.
  361. * @param length The number of bytes to update.
  362. * @throws java.lang.IllegalStateException If this instance has not
  363. * been initialized.
  364. */
  365. public final void update(byte[] input, int offset, int length)
  366. throws IllegalStateException
  367. {
  368. if (virgin)
  369. {
  370. throw new IllegalStateException("not initialized");
  371. }
  372. macSpi.engineUpdate(input, offset, length);
  373. }
  374. /**
  375. * Update this MAC with the remaining bytes in the given buffer
  376. * @param buffer The input buffer.
  377. * @since 1.5
  378. */
  379. public final void update (final ByteBuffer buffer)
  380. {
  381. if (virgin)
  382. throw new IllegalStateException ("not initialized");
  383. macSpi.engineUpdate(buffer);
  384. }
  385. /**
  386. * Clone this instance, if the underlying implementation supports it.
  387. *
  388. * @return A clone of this instance.
  389. * @throws java.lang.CloneNotSupportedException If the underlying
  390. * implementation is not cloneable.
  391. */
  392. public final Object clone() throws CloneNotSupportedException
  393. {
  394. Mac result = new Mac((MacSpi) macSpi.clone(), provider, algorithm);
  395. result.virgin = virgin;
  396. return result;
  397. }
  398. }