CipherSpi.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /* CipherSpi.java -- The cipher service provider interface.
  2. Copyright (C) 2004, 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 javax.crypto;
  32. import java.nio.ByteBuffer;
  33. import java.security.AlgorithmParameters;
  34. import java.security.InvalidAlgorithmParameterException;
  35. import java.security.InvalidKeyException;
  36. import java.security.Key;
  37. import java.security.NoSuchAlgorithmException;
  38. import java.security.SecureRandom;
  39. import java.security.spec.AlgorithmParameterSpec;
  40. /**
  41. * <p>This class represents the <i>Service Provider Interface</i>
  42. * (<b>SPI</b>) for cryptographic ciphers.</p>
  43. *
  44. * <p>Providers of cryptographic ciphers must subclass this for every
  45. * cipher they implement, implementing the abstract methods as
  46. * appropriate, then provide an entry that points to the subclass in
  47. * their implementation of {@link java.security.Provider}.</p>
  48. *
  49. * <p>CipherSpi objects are instantiated along with {@link Cipher}s when
  50. * the {@link Cipher#getInstance(java.lang.String)} methods are invoked.
  51. * Particular ciphers are referenced by a <i>transformation</i>, which
  52. * is a String consisting of the cipher's name or the ciper's name
  53. * followed by a mode and a padding. Transformations all follow the
  54. * general form:</p>
  55. *
  56. * <ul>
  57. * <li><i>algorithm</i>, or</li>
  58. * <li><i>algorithm</i>/<i>mode</i>/<i>padding</i>
  59. * </ul>
  60. *
  61. * <p>Cipher names in the master {@link java.security.Provider} class
  62. * may be:</p>
  63. *
  64. * <ol>
  65. * <li>The algorithm's name, which uses a pluggable mode and padding:
  66. * <code>Cipher.<i>algorithm</i></code></li>
  67. * <li>The algorithm's name and the mode, which uses pluggable padding:
  68. * <code>Cipher.<i>algorithm</i>/<i>mode</i></code></li>
  69. * <li>The algorithm's name and the padding, which uses a pluggable
  70. * mode: <code>Cipher.<i>algorithm</i>//<i>padding</i></code></li>
  71. * <li>The algorihtm's name, the mode, and the padding:
  72. * <code>Cipher.<i>algorithm</i>/<i>mode</i>/<i>padding</i></code></li>
  73. * </ol>
  74. *
  75. * <p>When any {@link Cipher#getInstance(java.lang.String)} method is
  76. * invoked, the following happens if the transformation is simply
  77. * <i>algorithm</i>:</p>
  78. *
  79. * <ol>
  80. * <li>If the provider defines a <code>CipherSpi</code> implementation
  81. * for "<i>algorithm</i>", return it. Otherwise throw a {@link
  82. * java.security.NoSuchAlgorithmException}.</li>
  83. * </ol>
  84. *
  85. * <p>If the transformation is of the form
  86. * <i>algorithm</i>/<i>mode</i>/<i>padding</i>:</p>
  87. *
  88. * <ol>
  89. * <li>If the provider defines a <code>CipherSpi</code> subclass for
  90. * "<i>algorithm</i>/<i>mode</i>/<i>padding</i>", return it. Otherwise
  91. * go to step 2.</li>
  92. *
  93. * <li>If the provider defines a <code>CipherSpi</code> subclass for
  94. * "<i>algorithm</i>/<i>mode</i>", instatiate it, call {@link
  95. * #engineSetPadding(java.lang.String)} for the padding name, and return
  96. * it. Otherwise go to step 3.</li>
  97. *
  98. * <li>If the provider defines a <code>CipherSpi</code> subclass for
  99. * "<i>algorithm</i>//<i>padding</i>", instatiate it, call {@link
  100. * #engineSetMode(java.lang.String)} for the mode name, and return
  101. * it. Otherwise go to step 4.</li>
  102. *
  103. * <li>If the provider defines a <code>CipherSpi</code> subclass for
  104. * "<i>algorithm</i>", instatiate it, call {@link
  105. * #engineSetMode(java.lang.String)} for the mode name, call {@link
  106. * #engineSetPadding(java.lang.String)} for the padding name, and return
  107. * it. Otherwise throw a {@link java.security.NoSuchAlgorithmException}.</li>
  108. * </ol>
  109. *
  110. * @author Casey Marshall (csm@gnu.org)
  111. * @since 1.4
  112. */
  113. public abstract class CipherSpi
  114. {
  115. // Constructors.
  116. // ------------------------------------------------------------------------
  117. /**
  118. * Create a new CipherSpi.
  119. */
  120. public CipherSpi()
  121. {
  122. }
  123. // Abstract methods to be implemented by providers.
  124. // ------------------------------------------------------------------------
  125. /**
  126. * Finishes a multi-part transformation or transforms a portion of a
  127. * byte array, and returns the transformed bytes.
  128. *
  129. * @param input The input bytes.
  130. * @param inputOffset The index in the input at which to start.
  131. * @param inputLength The number of bytes to transform.
  132. * @return The transformed bytes in a new array.
  133. * @throws javax.crypto.IllegalBlockSizeException If this instance has
  134. * no padding and the input size is not a multiple of the
  135. * block size.
  136. * @throws javax.crypto.BadPaddingException If this instance is being
  137. * used for decryption and the padding is not appropriate for
  138. * this instance's padding scheme.
  139. */
  140. protected abstract byte[]
  141. engineDoFinal(byte[] input, int inputOffset, int inputLength)
  142. throws IllegalBlockSizeException, BadPaddingException;
  143. /**
  144. * Finishes a multi-part transformation or transforms a portion of a
  145. * byte array, and stores the transformed bytes in the supplied array.
  146. *
  147. * @param input The input bytes.
  148. * @param inputOffset The index in the input at which to start.
  149. * @param inputLength The number of bytes to transform.
  150. * @param output The output byte array.
  151. * @param outputOffset The index in the output array at which to start.
  152. * @return The number of transformed bytes stored in the output array.
  153. * @throws javax.crypto.IllegalBlockSizeException If this instance has
  154. * no padding and the input size is not a multiple of the
  155. * block size.
  156. * @throws javax.crypto.BadPaddingException If this instance is being
  157. * used for decryption and the padding is not appropriate for
  158. * this instance's padding scheme.
  159. * @throws javax.crypto.ShortBufferException If there is not enough
  160. * space in the output array for the transformed bytes.
  161. */
  162. protected abstract int
  163. engineDoFinal(byte[] input, int inputOffset, int inputLength,
  164. byte[] output, int outputOffset)
  165. throws IllegalBlockSizeException, BadPaddingException, ShortBufferException;
  166. /**
  167. * @since 1.5
  168. */
  169. protected int engineDoFinal (ByteBuffer input, ByteBuffer output)
  170. throws BadPaddingException, IllegalBlockSizeException,
  171. ShortBufferException
  172. {
  173. int total = 0;
  174. byte[] inbuf = new byte[256];
  175. while (input.hasRemaining ())
  176. {
  177. int in = Math.min (inbuf.length, input.remaining ());
  178. input.get (inbuf, 0, in);
  179. byte[] outbuf = new byte[engineGetOutputSize (in)];
  180. int out = 0;
  181. if (input.hasRemaining ()) // i.e., we have more 'update' calls
  182. out = engineUpdate (inbuf, 0, in, outbuf, 0);
  183. else
  184. out = engineDoFinal (inbuf, 0, in, outbuf, 0);
  185. output.put (outbuf, 0, out);
  186. total += out;
  187. }
  188. return total;
  189. }
  190. /**
  191. * Returns the block size of the underlying cipher.
  192. *
  193. * @return The block size.
  194. */
  195. protected abstract int engineGetBlockSize();
  196. /**
  197. * Returns the initializaiton vector this cipher was initialized with,
  198. * if any.
  199. *
  200. * @return The IV, or null if this cipher uses no IV or if this
  201. * instance has not been initialized yet.
  202. */
  203. protected abstract byte[] engineGetIV();
  204. /**
  205. * <p>Return the length of the given key in bits.</p>
  206. *
  207. * <p>For compatibility this method is not declared
  208. * <code>abstract</code>, and the default implementation will throw an
  209. * {@link java.lang.UnsupportedOperationException}. Concrete
  210. * subclasses should override this method to return the correct
  211. * value.</p>
  212. *
  213. * @param key The key to get the size for.
  214. * @return The size of the key, in bits.
  215. * @throws java.security.InvalidKeyException If the key's length
  216. * cannot be determined by this implementation.
  217. */
  218. protected int engineGetKeySize(Key key) throws InvalidKeyException
  219. {
  220. throw new UnsupportedOperationException();
  221. }
  222. /**
  223. * <p>Returns the size, in bytes, an output buffer must be for a call
  224. * to {@link #engineUpdate(byte[],int,int,byte[],int)} or {@link
  225. * #engineDoFinal(byte[],int,int,byte[],int)} to succeed.</p>
  226. *
  227. * <p>The actual output length may be smaller than the value returned
  228. * by this method, as it considers the padding length as well. The
  229. * length considered is the argument plus the length of any buffered,
  230. * unprocessed bytes.</p>
  231. *
  232. * @param inputLength The input length, in bytes.
  233. * @return The size an output buffer must be.
  234. */
  235. protected abstract int engineGetOutputSize(int inputLength);
  236. /**
  237. * Returns the parameters that this cipher is using. This may be the
  238. * parameters used to initialize this cipher, or it may be parameters
  239. * that have been initialized with random values.
  240. *
  241. * @return This cipher's parameters, or <code>null</code> if this
  242. * cipher does not use parameters.
  243. */
  244. protected abstract AlgorithmParameters engineGetParameters();
  245. /**
  246. * Initializes this cipher with an operation mode, key, and source of
  247. * randomness. If this cipher requires any other initializing data,
  248. * for example an initialization vector, then it should generate it
  249. * from the provided source of randomness.
  250. *
  251. * @param opmode The operation mode, one of {@link
  252. * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
  253. * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
  254. * @param key The key to initialize this cipher with.
  255. * @param random The source of random bytes to use.
  256. * @throws java.security.InvalidKeyException If the given key is not
  257. * acceptable for this implementation.
  258. */
  259. protected abstract void engineInit(int opmode, Key key, SecureRandom random)
  260. throws InvalidKeyException;
  261. /**
  262. * Initializes this cipher with an operation mode, key, parameters,
  263. * and source of randomness. If this cipher requires any other
  264. * initializing data, for example an initialization vector, then it should
  265. * generate it from the provided source of randomness.
  266. *
  267. * @param opmode The operation mode, one of {@link
  268. * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
  269. * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
  270. * @param key The key to initialize this cipher with.
  271. * @param params The algorithm parameters to initialize with.
  272. * @param random The source of random bytes to use.
  273. * @throws java.security.InvalidAlgorithmParameterException If the
  274. * given parameters are not appropriate for this
  275. * implementation.
  276. * @throws java.security.InvalidKeyException If the given key is not
  277. * acceptable for this implementation.
  278. */
  279. protected abstract void
  280. engineInit(int opmode, Key key, AlgorithmParameters params,
  281. SecureRandom random)
  282. throws InvalidAlgorithmParameterException, InvalidKeyException;
  283. /**
  284. * Initializes this cipher with an operation mode, key, parameters,
  285. * and source of randomness. If this cipher requires any other
  286. * initializing data, for example an initialization vector, then it should
  287. * generate it from the provided source of randomness.
  288. *
  289. * @param opmode The operation mode, one of {@link
  290. * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
  291. * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
  292. * @param key The key to initialize this cipher with.
  293. * @param params The algorithm parameters to initialize with.
  294. * @param random The source of random bytes to use.
  295. * @throws java.security.InvalidAlgorithmParameterException If the
  296. * given parameters are not appropriate for this
  297. * implementation.
  298. * @throws java.security.InvalidKeyException If the given key is not
  299. * acceptable for this implementation.
  300. */
  301. protected abstract void
  302. engineInit(int opmode, Key key, AlgorithmParameterSpec params,
  303. SecureRandom random)
  304. throws InvalidAlgorithmParameterException, InvalidKeyException;
  305. /**
  306. * Set the mode in which this cipher is to run.
  307. *
  308. * @param mode The name of the mode to use.
  309. * @throws java.security.NoSuchAlgorithmException If the mode is
  310. * not supported by this cipher's provider.
  311. */
  312. protected abstract void engineSetMode(String mode)
  313. throws NoSuchAlgorithmException;
  314. /**
  315. * Set the method with which the input is to be padded.
  316. *
  317. * @param padding The name of the padding to use.
  318. * @throws javax.crypto.NoSuchPaddingException If the padding is not
  319. * supported by this cipher's provider.
  320. */
  321. protected abstract void engineSetPadding(String padding)
  322. throws NoSuchPaddingException;
  323. /**
  324. * <p>Unwraps a previously-wrapped key.</p>
  325. *
  326. * <p>For compatibility this method is not declared
  327. * <code>abstract</code>, and the default implementation will throw an
  328. * {@link java.lang.UnsupportedOperationException}.</p>
  329. *
  330. * @param wrappedKey The wrapped key.
  331. * @param wrappedKeyAlgorithm The name of the algorithm used to wrap
  332. * this key.
  333. * @param wrappedKeyType The type of wrapped key; one of
  334. * {@link Cipher#PRIVATE_KEY},
  335. * {@link Cipher#PUBLIC_KEY}, or
  336. * {@link Cipher#SECRET_KEY}.
  337. * @return The unwrapped key.
  338. * @throws java.security.InvalidKeyException If the key cannot be
  339. * unwrapped, or if <code>wrappedKeyType</code> is an
  340. * inappropriate type for the unwrapped key.
  341. * @throws java.security.NoSuchAlgorithmException If the
  342. * <code>wrappedKeyAlgorithm</code> is unknown.
  343. */
  344. protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
  345. int wrappedKeyType)
  346. throws InvalidKeyException, NoSuchAlgorithmException
  347. {
  348. throw new UnsupportedOperationException();
  349. }
  350. /**
  351. * Continue with a multi-part transformation, returning a new array of
  352. * the transformed bytes.
  353. *
  354. * @param input The next input bytes.
  355. * @param inputOffset The index in the input array from which to start.
  356. * @param inputLength The number of bytes to input.
  357. * @return The transformed bytes.
  358. */
  359. protected abstract byte[]
  360. engineUpdate(byte[] input, int inputOffset, int inputLength);
  361. /**
  362. * Continue with a multi-part transformation, storing the transformed
  363. * bytes into the specified array.
  364. *
  365. * @param input The next input bytes.
  366. * @param inputOffset The index in the input from which to start.
  367. * @param inputLength The number of bytes to input.
  368. * @param output The output buffer.
  369. * @param outputOffset The index in the output array from which to start.
  370. * @return The transformed bytes.
  371. * @throws javax.crypto.ShortBufferException If there is not enough
  372. * space in the output array to store the transformed bytes.
  373. */
  374. protected abstract int
  375. engineUpdate(byte[] input, int inputOffset, int inputLength,
  376. byte[] output, int outputOffset)
  377. throws ShortBufferException;
  378. /**
  379. * @since 1.5
  380. */
  381. protected int engineUpdate (ByteBuffer input, ByteBuffer output)
  382. throws ShortBufferException
  383. {
  384. int total = 0;
  385. byte[] inbuf = new byte[256];
  386. while (input.hasRemaining ())
  387. {
  388. int in = Math.min (inbuf.length, input.remaining ());
  389. input.get (inbuf, 0, in);
  390. byte[] outbuf = new byte[engineGetOutputSize (in)];
  391. int out = engineUpdate (inbuf, 0, in, outbuf, 0);
  392. output.put (outbuf, 0, out);
  393. total += out;
  394. }
  395. return total;
  396. }
  397. /**
  398. * <p>Wrap a key.</p>
  399. *
  400. * <p>For compatibility this method is not declared
  401. * <code>abstract</code>, and the default implementation will throw an
  402. * {@link java.lang.UnsupportedOperationException}.</p>
  403. *
  404. * @param key The key to wrap.
  405. * @return The wrapped key.
  406. * @throws java.security.InvalidKeyException If the key cannot be
  407. * wrapped.
  408. */
  409. protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException
  410. {
  411. throw new UnsupportedOperationException();
  412. }
  413. }