BaseMode.java 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /* BaseMode.java --
  2. Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
  3. This file is a 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 of the License, or (at
  7. your option) 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; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  15. 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 gnu.javax.crypto.mode;
  32. import gnu.java.lang.CPStringBuilder;
  33. import gnu.javax.crypto.cipher.IBlockCipher;
  34. import java.security.InvalidKeyException;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.Collections;
  38. import java.util.HashMap;
  39. import java.util.Iterator;
  40. import java.util.Map;
  41. /**
  42. * A basic abstract class to facilitate implementing block cipher modes of
  43. * operations.
  44. */
  45. public abstract class BaseMode
  46. implements IMode
  47. {
  48. /** The canonical name prefix of this mode. */
  49. protected String name;
  50. /** The state indicator of this instance. */
  51. protected int state;
  52. /** The underlying block cipher implementation. */
  53. protected IBlockCipher cipher;
  54. /** The block size, in bytes, to operate the underlying block cipher in. */
  55. protected int cipherBlockSize;
  56. /** The block size, in bytes, in which to operate the mode instance. */
  57. protected int modeBlockSize;
  58. /** The initialisation vector value. */
  59. protected byte[] iv;
  60. /** The instance lock. */
  61. protected Object lock = new Object();
  62. /**
  63. * Trivial constructor for use by concrete subclasses.
  64. *
  65. * @param name the canonical name prefix of this mode.
  66. * @param underlyingCipher the implementation of the underlying cipher.
  67. * @param cipherBlockSize the block size, in bytes, in which to operate the
  68. * underlying cipher.
  69. */
  70. protected BaseMode(String name, IBlockCipher underlyingCipher,
  71. int cipherBlockSize)
  72. {
  73. super();
  74. this.name = name;
  75. this.cipher = underlyingCipher;
  76. this.cipherBlockSize = cipherBlockSize;
  77. state = -1;
  78. }
  79. public void update(byte[] in, int inOffset, byte[] out, int outOffset)
  80. throws IllegalStateException
  81. {
  82. synchronized (lock)
  83. {
  84. switch (state)
  85. {
  86. case ENCRYPTION:
  87. encryptBlock(in, inOffset, out, outOffset);
  88. break;
  89. case DECRYPTION:
  90. decryptBlock(in, inOffset, out, outOffset);
  91. break;
  92. default:
  93. throw new IllegalStateException();
  94. }
  95. }
  96. }
  97. public String name()
  98. {
  99. return new CPStringBuilder(name).append('(').append(cipher.name()).append(')')
  100. .toString();
  101. }
  102. /**
  103. * Returns the default value, in bytes, of the mode's block size. This value
  104. * is part of the construction arguments passed to the Factory methods in
  105. * {@link ModeFactory}. Unless changed by an invocation of any of the
  106. * <code>init()</code> methods, a <i>Mode</i> instance would operate with
  107. * the same block size as its underlying block cipher. As mentioned earlier,
  108. * the block size of the underlying block cipher itself is specified in one of
  109. * the method(s) available in the factory class.
  110. *
  111. * @return the default value, in bytes, of the mode's block size.
  112. * @see ModeFactory
  113. */
  114. public int defaultBlockSize()
  115. {
  116. return cipherBlockSize;
  117. }
  118. /**
  119. * Returns the default value, in bytes, of the underlying block cipher key
  120. * size.
  121. *
  122. * @return the default value, in bytes, of the underlying cipher's key size.
  123. */
  124. public int defaultKeySize()
  125. {
  126. return cipher.defaultKeySize();
  127. }
  128. /**
  129. * Returns an {@link Iterator} over the supported block sizes. Each element
  130. * returned by this object is an {@link Integer}.
  131. * <p>
  132. * The default behaviour is to return an iterator with just one value, which
  133. * is that currently configured for the underlying block cipher. Concrete
  134. * implementations may override this behaviour to signal their ability to
  135. * support other values.
  136. *
  137. * @return an {@link Iterator} over the supported block sizes.
  138. */
  139. public Iterator blockSizes()
  140. {
  141. ArrayList al = new ArrayList();
  142. al.add(Integer.valueOf(cipherBlockSize));
  143. return Collections.unmodifiableList(al).iterator();
  144. }
  145. /**
  146. * Returns an {@link Iterator} over the supported underlying block cipher key
  147. * sizes. Each element returned by this object is an instance of
  148. * {@link Integer}.
  149. *
  150. * @return an {@link Iterator} over the supported key sizes.
  151. */
  152. public Iterator keySizes()
  153. {
  154. return cipher.keySizes();
  155. }
  156. public void init(Map attributes) throws InvalidKeyException,
  157. IllegalStateException
  158. {
  159. synchronized (lock)
  160. {
  161. if (state != -1)
  162. throw new IllegalStateException();
  163. Integer want = (Integer) attributes.get(STATE);
  164. if (want != null)
  165. {
  166. switch (want.intValue())
  167. {
  168. case ENCRYPTION:
  169. state = ENCRYPTION;
  170. break;
  171. case DECRYPTION:
  172. state = DECRYPTION;
  173. break;
  174. default:
  175. throw new IllegalArgumentException();
  176. }
  177. }
  178. Integer bs = (Integer) attributes.get(MODE_BLOCK_SIZE);
  179. modeBlockSize = (bs == null ? cipherBlockSize : bs.intValue());
  180. byte[] iv = (byte[]) attributes.get(IV);
  181. if (iv != null)
  182. this.iv = (byte[]) iv.clone();
  183. else
  184. this.iv = new byte[modeBlockSize];
  185. cipher.init(attributes);
  186. setup();
  187. }
  188. }
  189. public int currentBlockSize()
  190. {
  191. if (state == -1)
  192. throw new IllegalStateException();
  193. return modeBlockSize;
  194. }
  195. public void reset()
  196. {
  197. synchronized (lock)
  198. {
  199. state = -1;
  200. iv = null;
  201. cipher.reset();
  202. teardown();
  203. }
  204. }
  205. public boolean selfTest()
  206. {
  207. int ks;
  208. Iterator bit;
  209. for (Iterator kit = keySizes(); kit.hasNext();)
  210. {
  211. ks = ((Integer) kit.next()).intValue();
  212. for (bit = blockSizes(); bit.hasNext();)
  213. if (! testSymmetry(ks, ((Integer) bit.next()).intValue()))
  214. return false;
  215. }
  216. return true;
  217. }
  218. public abstract Object clone();
  219. /** The initialisation phase of the concrete mode implementation. */
  220. public abstract void setup();
  221. /** The termination phase of the concrete mode implementation. */
  222. public abstract void teardown();
  223. public abstract void encryptBlock(byte[] in, int i, byte[] out, int o);
  224. public abstract void decryptBlock(byte[] in, int i, byte[] out, int o);
  225. private boolean testSymmetry(int ks, int bs)
  226. {
  227. try
  228. {
  229. IMode mode = (IMode) this.clone();
  230. byte[] iv = new byte[cipherBlockSize]; // all zeroes
  231. byte[] k = new byte[ks];
  232. int i;
  233. for (i = 0; i < ks; i++)
  234. k[i] = (byte) i;
  235. int blockCount = 5;
  236. int limit = blockCount * bs;
  237. byte[] pt = new byte[limit];
  238. for (i = 0; i < limit; i++)
  239. pt[i] = (byte) i;
  240. byte[] ct = new byte[limit];
  241. byte[] cpt = new byte[limit];
  242. Map map = new HashMap();
  243. map.put(KEY_MATERIAL, k);
  244. map.put(CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
  245. map.put(STATE, Integer.valueOf(ENCRYPTION));
  246. map.put(IV, iv);
  247. map.put(MODE_BLOCK_SIZE, Integer.valueOf(bs));
  248. mode.reset();
  249. mode.init(map);
  250. for (i = 0; i < blockCount; i++)
  251. mode.update(pt, i * bs, ct, i * bs);
  252. mode.reset();
  253. map.put(STATE, Integer.valueOf(DECRYPTION));
  254. mode.init(map);
  255. for (i = 0; i < blockCount; i++)
  256. mode.update(ct, i * bs, cpt, i * bs);
  257. return Arrays.equals(pt, cpt);
  258. }
  259. catch (Exception x)
  260. {
  261. x.printStackTrace(System.err);
  262. return false;
  263. }
  264. }
  265. }