Cascade.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /* Cascade.java --
  2. Copyright (C) 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.assembly;
  32. import java.math.BigInteger;
  33. import java.security.InvalidKeyException;
  34. import java.util.Collections;
  35. import java.util.HashMap;
  36. import java.util.HashSet;
  37. import java.util.Iterator;
  38. import java.util.LinkedList;
  39. import java.util.Map;
  40. import java.util.Set;
  41. /**
  42. * A <i>Cascade</i> Cipher is the concatenation of two or more block ciphers
  43. * each with independent keys. Plaintext is input to the first stage; the output
  44. * of stage <code>i</code> is input to stage <code>i + 1</code>; and the
  45. * output of the last stage is the <i>Cascade</i>'s ciphertext output.
  46. * <p>
  47. * In the simplest case, all stages in a <code>Cascade</code> have <i>k</i>-bit
  48. * keys, and the stage inputs and outputs are all n-bit quantities. The stage
  49. * ciphers may differ (general cascade of ciphers), or all be identical (cascade
  50. * of identical ciphers).
  51. * <p>
  52. * The term "block ciphers" used above refers to implementations of
  53. * {@link gnu.javax.crypto.mode.IMode}, including the
  54. * {@link gnu.javax.crypto.mode.ECB} mode which basically exposes a
  55. * symmetric-key block cipher algorithm as a <i>Mode</i> of Operations.
  56. * <p>
  57. * References:
  58. * <ol>
  59. * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of
  60. * Applied Cryptography.<br>
  61. * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br>
  62. * Menezes, A., van Oorschot, P. and S. Vanstone.</li>
  63. * </ol>
  64. */
  65. public class Cascade
  66. {
  67. public static final String DIRECTION = "gnu.crypto.assembly.cascade.direction";
  68. /** The map of Stages chained in this cascade. */
  69. protected HashMap stages;
  70. /** The ordered list of Stage UIDs to their attribute maps. */
  71. protected LinkedList stageKeys;
  72. /** The current operational direction of this instance. */
  73. protected Direction wired;
  74. /** The curently set block-size for this instance. */
  75. protected int blockSize;
  76. public Cascade()
  77. {
  78. super();
  79. stages = new HashMap(3);
  80. stageKeys = new LinkedList();
  81. wired = null;
  82. blockSize = 0;
  83. }
  84. /**
  85. * Returns the Least Common Multiple of two integers.
  86. *
  87. * @param a the first integer.
  88. * @param b the second integer.
  89. * @return the LCM of <code>abs(a)</code> and <code>abs(b)</code>.
  90. */
  91. private static final int lcm(int a, int b)
  92. {
  93. BigInteger A = BigInteger.valueOf(a * 1L);
  94. BigInteger B = BigInteger.valueOf(b * 1L);
  95. return A.multiply(B).divide(A.gcd(B)).abs().intValue();
  96. }
  97. /**
  98. * Adds to the end of the current chain, a designated {@link Stage}.
  99. *
  100. * @param stage the {@link Stage} to append to the chain.
  101. * @return a unique identifier for this stage, within this cascade.
  102. * @throws IllegalStateException if the instance is already initialised.
  103. * @throws IllegalArgumentException if the designated stage is already in the
  104. * chain, or it has incompatible characteristics with the current
  105. * elements already in the chain.
  106. */
  107. public Object append(Stage stage) throws IllegalArgumentException
  108. {
  109. return insert(size(), stage);
  110. }
  111. /**
  112. * Adds to the begining of the current chain, a designated {@link Stage}.
  113. *
  114. * @param stage the {@link Stage} to prepend to the chain.
  115. * @return a unique identifier for this stage, within this cascade.
  116. * @throws IllegalStateException if the instance is already initialised.
  117. * @throws IllegalArgumentException if the designated stage is already in the
  118. * chain, or it has incompatible characteristics with the current
  119. * elements already in the chain.
  120. */
  121. public Object prepend(Stage stage) throws IllegalArgumentException
  122. {
  123. return insert(0, stage);
  124. }
  125. /**
  126. * Inserts a {@link Stage} into the current chain, at the specified index
  127. * (zero-based) position.
  128. *
  129. * @param stage the {@link Stage} to insert into the chain.
  130. * @return a unique identifier for this stage, within this cascade.
  131. * @throws IllegalArgumentException if the designated stage is already in the
  132. * chain, or it has incompatible characteristics with the current
  133. * elements already in the chain.
  134. * @throws IllegalStateException if the instance is already initialised.
  135. * @throws IndexOutOfBoundsException if <code>index</code> is less than
  136. * <code>0</code> or greater than the current size of this
  137. * cascade.
  138. */
  139. public Object insert(int index, Stage stage) throws IllegalArgumentException,
  140. IndexOutOfBoundsException
  141. {
  142. if (stages.containsValue(stage))
  143. throw new IllegalArgumentException();
  144. if (wired != null || stage == null)
  145. throw new IllegalStateException();
  146. if (index < 0 || index > size())
  147. throw new IndexOutOfBoundsException();
  148. // check that there is a non-empty set of common block-sizes
  149. Set set = stage.blockSizes();
  150. if (stages.isEmpty())
  151. {
  152. if (set.isEmpty())
  153. throw new IllegalArgumentException("1st stage with no block sizes");
  154. }
  155. else
  156. {
  157. Set common = this.blockSizes();
  158. common.retainAll(set);
  159. if (common.isEmpty())
  160. throw new IllegalArgumentException("no common block sizes found");
  161. }
  162. Object result = new Object();
  163. stageKeys.add(index, result);
  164. stages.put(result, stage);
  165. return result;
  166. }
  167. /**
  168. * Returns the current number of stages in this chain.
  169. *
  170. * @return the current count of stages in this chain.
  171. */
  172. public int size()
  173. {
  174. return stages.size();
  175. }
  176. /**
  177. * Returns an {@link Iterator} over the stages contained in this instance.
  178. * Each element of this iterator is a concrete implementation of a {@link
  179. * Stage}.
  180. *
  181. * @return an {@link Iterator} over the stages contained in this instance.
  182. * Each element of the returned iterator is a concrete instance of a
  183. * {@link Stage}.
  184. */
  185. public Iterator stages()
  186. {
  187. LinkedList result = new LinkedList();
  188. for (Iterator it = stageKeys.listIterator(); it.hasNext();)
  189. result.addLast(stages.get(it.next()));
  190. return result.listIterator();
  191. }
  192. /**
  193. * Returns the {@link Set} of supported block sizes for this
  194. * <code>Cascade</code> that are common to all of its chained stages. Each
  195. * element in the returned {@link Set} is an instance of {@link Integer}.
  196. *
  197. * @return a {@link Set} of supported block sizes common to all the stages of
  198. * the chain.
  199. */
  200. public Set blockSizes()
  201. {
  202. HashSet result = null;
  203. for (Iterator it = stages.values().iterator(); it.hasNext();)
  204. {
  205. Stage aStage = (Stage) it.next();
  206. if (result == null) // first time
  207. result = new HashSet(aStage.blockSizes());
  208. else
  209. result.retainAll(aStage.blockSizes());
  210. }
  211. return result == null ? Collections.EMPTY_SET : result;
  212. }
  213. /**
  214. * Initialises the chain for operation with specific characteristics.
  215. *
  216. * @param attributes a set of name-value pairs that describes the desired
  217. * future behaviour of this instance.
  218. * @throws IllegalStateException if the chain, or any of its stages, is
  219. * already initialised.
  220. * @throws InvalidKeyException if the intialisation data provided with the
  221. * stage is incorrect or causes an invalid key to be generated.
  222. * @see Direction#FORWARD
  223. * @see Direction#REVERSED
  224. */
  225. public void init(Map attributes) throws InvalidKeyException
  226. {
  227. if (wired != null)
  228. throw new IllegalStateException();
  229. Direction flow = (Direction) attributes.get(DIRECTION);
  230. if (flow == null)
  231. flow = Direction.FORWARD;
  232. int optimalSize = 0;
  233. for (Iterator it = stageKeys.listIterator(); it.hasNext();)
  234. {
  235. Object id = it.next();
  236. Map attr = (Map) attributes.get(id);
  237. attr.put(Stage.DIRECTION, flow);
  238. Stage stage = (Stage) stages.get(id);
  239. stage.init(attr);
  240. optimalSize = optimalSize == 0 ? stage.currentBlockSize()
  241. : lcm(optimalSize,
  242. stage.currentBlockSize());
  243. }
  244. if (flow == Direction.REVERSED) // reverse order
  245. Collections.reverse(stageKeys);
  246. wired = flow;
  247. blockSize = optimalSize;
  248. }
  249. /**
  250. * Returns the currently set block size for the chain.
  251. *
  252. * @return the current block size for the chain.
  253. * @throws IllegalStateException if the instance is not initialised.
  254. */
  255. public int currentBlockSize()
  256. {
  257. if (wired == null)
  258. throw new IllegalStateException();
  259. return blockSize;
  260. }
  261. /**
  262. * Resets the chain for re-initialisation and use with other characteristics.
  263. * This method always succeeds.
  264. */
  265. public void reset()
  266. {
  267. for (Iterator it = stageKeys.listIterator(); it.hasNext();)
  268. ((Stage) stages.get(it.next())).reset();
  269. if (wired == Direction.REVERSED) // reverse it back
  270. Collections.reverse(stageKeys);
  271. wired = null;
  272. blockSize = 0;
  273. }
  274. /**
  275. * Processes exactly one block of <i>plaintext</i> (if initialised in the
  276. * {@link Direction#FORWARD} state) or <i>ciphertext</i> (if initialised in
  277. * the {@link Direction#REVERSED} state).
  278. *
  279. * @param in the plaintext.
  280. * @param inOffset index of <code>in</code> from which to start considering
  281. * data.
  282. * @param out the ciphertext.
  283. * @param outOffset index of <code>out</code> from which to store result.
  284. * @throws IllegalStateException if the instance is not initialised.
  285. */
  286. public void update(byte[] in, int inOffset, byte[] out, int outOffset)
  287. {
  288. if (wired == null)
  289. throw new IllegalStateException();
  290. int stageBlockSize, j, i = stages.size();
  291. for (Iterator it = stageKeys.listIterator(); it.hasNext();)
  292. {
  293. Stage stage = (Stage) stages.get(it.next());
  294. stageBlockSize = stage.currentBlockSize();
  295. for (j = 0; j < blockSize; j += stageBlockSize)
  296. stage.update(in, inOffset + j, out, outOffset + j);
  297. i--;
  298. if (i > 0)
  299. System.arraycopy(out, outOffset, in, inOffset, blockSize);
  300. }
  301. }
  302. /**
  303. * Conducts a simple <i>correctness</i> test that consists of basic symmetric
  304. * encryption / decryption test(s) for all supported block and key sizes of
  305. * underlying block cipher(s) wrapped by Mode leafs. The test also includes
  306. * one (1) variable key Known Answer Test (KAT) for each block cipher.
  307. *
  308. * @return <code>true</code> if the implementation passes simple
  309. * <i>correctness</i> tests. Returns <code>false</code> otherwise.
  310. */
  311. public boolean selfTest()
  312. {
  313. for (Iterator it = stageKeys.listIterator(); it.hasNext();)
  314. {
  315. if (! ((Stage) stages.get(it.next())).selfTest())
  316. return false;
  317. }
  318. return true;
  319. }
  320. }