Cascade.java 12.1 KB
Newer Older
1
/* Cascade.java --
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
   Copyright (C) 2003, 2006 Free Software Foundation, Inc.

This file is a part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package gnu.javax.crypto.assembly;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

/**
52
 * A <i>Cascade</i> Cipher is the concatenation of two or more block ciphers
53
 * each with independent keys. Plaintext is input to the first stage; the output
54 55 56 57
 * of stage <code>i</code> is input to stage <code>i + 1</code>; and the
 * output of the last stage is the <i>Cascade</i>'s ciphertext output.
 * <p>
 * In the simplest case, all stages in a <code>Cascade</code> have <i>k</i>-bit
58 59
 * keys, and the stage inputs and outputs are all n-bit quantities. The stage
 * ciphers may differ (general cascade of ciphers), or all be identical (cascade
60 61 62 63 64 65 66 67
 * of identical ciphers).
 * <p>
 * The term "block ciphers" used above refers to implementations of
 * {@link gnu.javax.crypto.mode.IMode}, including the
 * {@link gnu.javax.crypto.mode.ECB} mode which basically exposes a
 * symmetric-key block cipher algorithm as a <i>Mode</i> of Operations.
 * <p>
 * References:
68
 * <ol>
69 70 71 72
 * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of
 * Applied Cryptography.<br>
 * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br>
 * Menezes, A., van Oorschot, P. and S. Vanstone.</li>
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 * </ol>
 */
public class Cascade
{
  public static final String DIRECTION = "gnu.crypto.assembly.cascade.direction";

  /** The map of Stages chained in this cascade. */
  protected HashMap stages;

  /** The ordered list of Stage UIDs to their attribute maps. */
  protected LinkedList stageKeys;

  /** The current operational direction of this instance. */
  protected Direction wired;

  /** The curently set block-size for this instance. */
  protected int blockSize;

  public Cascade()
  {
    super();

    stages = new HashMap(3);
    stageKeys = new LinkedList();
    wired = null;
    blockSize = 0;
  }

  /**
   * Returns the Least Common Multiple of two integers.
103
   *
104 105 106 107 108 109 110 111 112 113 114 115 116
   * @param a the first integer.
   * @param b the second integer.
   * @return the LCM of <code>abs(a)</code> and <code>abs(b)</code>.
   */
  private static final int lcm(int a, int b)
  {
    BigInteger A = BigInteger.valueOf(a * 1L);
    BigInteger B = BigInteger.valueOf(b * 1L);
    return A.multiply(B).divide(A.gcd(B)).abs().intValue();
  }

  /**
   * Adds to the end of the current chain, a designated {@link Stage}.
117
   *
118 119 120
   * @param stage the {@link Stage} to append to the chain.
   * @return a unique identifier for this stage, within this cascade.
   * @throws IllegalStateException if the instance is already initialised.
121 122 123
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
124 125 126 127 128 129 130 131
   */
  public Object append(Stage stage) throws IllegalArgumentException
  {
    return insert(size(), stage);
  }

  /**
   * Adds to the begining of the current chain, a designated {@link Stage}.
132
   *
133 134 135
   * @param stage the {@link Stage} to prepend to the chain.
   * @return a unique identifier for this stage, within this cascade.
   * @throws IllegalStateException if the instance is already initialised.
136 137 138
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
139 140 141 142 143 144 145 146 147
   */
  public Object prepend(Stage stage) throws IllegalArgumentException
  {
    return insert(0, stage);
  }

  /**
   * Inserts a {@link Stage} into the current chain, at the specified index
   * (zero-based) position.
148
   *
149 150
   * @param stage the {@link Stage} to insert into the chain.
   * @return a unique identifier for this stage, within this cascade.
151 152 153
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
154 155
   * @throws IllegalStateException if the instance is already initialised.
   * @throws IndexOutOfBoundsException if <code>index</code> is less than
156 157
   *           <code>0</code> or greater than the current size of this
   *           cascade.
158 159 160 161 162
   */
  public Object insert(int index, Stage stage) throws IllegalArgumentException,
      IndexOutOfBoundsException
  {
    if (stages.containsValue(stage))
163
      throw new IllegalArgumentException();
164
    if (wired != null || stage == null)
165
      throw new IllegalStateException();
166
    if (index < 0 || index > size())
167
      throw new IndexOutOfBoundsException();
168 169 170 171 172
    // check that there is a non-empty set of common block-sizes
    Set set = stage.blockSizes();
    if (stages.isEmpty())
      {
        if (set.isEmpty())
173
          throw new IllegalArgumentException("1st stage with no block sizes");
174 175 176 177 178 179
      }
    else
      {
        Set common = this.blockSizes();
        common.retainAll(set);
        if (common.isEmpty())
180
          throw new IllegalArgumentException("no common block sizes found");
181 182 183 184 185 186 187 188 189
      }
    Object result = new Object();
    stageKeys.add(index, result);
    stages.put(result, stage);
    return result;
  }

  /**
   * Returns the current number of stages in this chain.
190
   *
191 192 193 194 195 196 197 198 199 200 201
   * @return the current count of stages in this chain.
   */
  public int size()
  {
    return stages.size();
  }

  /**
   * Returns an {@link Iterator} over the stages contained in this instance.
   * Each element of this iterator is a concrete implementation of a {@link
   * Stage}.
202
   *
203
   * @return an {@link Iterator} over the stages contained in this instance.
204 205
   *         Each element of the returned iterator is a concrete instance of a
   *         {@link Stage}.
206 207 208 209 210
   */
  public Iterator stages()
  {
    LinkedList result = new LinkedList();
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
211
      result.addLast(stages.get(it.next()));
212 213 214 215 216 217 218
    return result.listIterator();
  }

  /**
   * Returns the {@link Set} of supported block sizes for this
   * <code>Cascade</code> that are common to all of its chained stages. Each
   * element in the returned {@link Set} is an instance of {@link Integer}.
219
   *
220 221
   * @return a {@link Set} of supported block sizes common to all the stages of
   *         the chain.
222 223 224 225 226 227 228
   */
  public Set blockSizes()
  {
    HashSet result = null;
    for (Iterator it = stages.values().iterator(); it.hasNext();)
      {
        Stage aStage = (Stage) it.next();
229 230
        if (result == null) // first time
          result = new HashSet(aStage.blockSizes());
231
        else
232
          result.retainAll(aStage.blockSizes());
233 234 235 236 237 238
      }
    return result == null ? Collections.EMPTY_SET : result;
  }

  /**
   * Initialises the chain for operation with specific characteristics.
239
   *
240
   * @param attributes a set of name-value pairs that describes the desired
241
   *          future behaviour of this instance.
242
   * @throws IllegalStateException if the chain, or any of its stages, is
243
   *           already initialised.
244
   * @throws InvalidKeyException if the intialisation data provided with the
245
   *           stage is incorrect or causes an invalid key to be generated.
246 247 248 249 250 251
   * @see Direction#FORWARD
   * @see Direction#REVERSED
   */
  public void init(Map attributes) throws InvalidKeyException
  {
    if (wired != null)
252
      throw new IllegalStateException();
253 254
    Direction flow = (Direction) attributes.get(DIRECTION);
    if (flow == null)
255
      flow = Direction.FORWARD;
256 257 258 259 260 261 262 263 264
    int optimalSize = 0;
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
      {
        Object id = it.next();
        Map attr = (Map) attributes.get(id);
        attr.put(Stage.DIRECTION, flow);
        Stage stage = (Stage) stages.get(id);
        stage.init(attr);
        optimalSize = optimalSize == 0 ? stage.currentBlockSize()
265 266
                                       : lcm(optimalSize,
                                             stage.currentBlockSize());
267
      }
268 269
    if (flow == Direction.REVERSED) // reverse order
      Collections.reverse(stageKeys);
270 271 272 273 274 275
    wired = flow;
    blockSize = optimalSize;
  }

  /**
   * Returns the currently set block size for the chain.
276
   *
277 278 279 280 281 282
   * @return the current block size for the chain.
   * @throws IllegalStateException if the instance is not initialised.
   */
  public int currentBlockSize()
  {
    if (wired == null)
283
      throw new IllegalStateException();
284 285 286 287 288 289 290 291 292 293
    return blockSize;
  }

  /**
   * Resets the chain for re-initialisation and use with other characteristics.
   * This method always succeeds.
   */
  public void reset()
  {
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
294 295 296
      ((Stage) stages.get(it.next())).reset();
    if (wired == Direction.REVERSED) // reverse it back
      Collections.reverse(stageKeys);
297 298 299 300 301 302
    wired = null;
    blockSize = 0;
  }

  /**
   * Processes exactly one block of <i>plaintext</i> (if initialised in the
303 304
   * {@link Direction#FORWARD} state) or <i>ciphertext</i> (if initialised in
   * the {@link Direction#REVERSED} state).
305
   *
306 307
   * @param in the plaintext.
   * @param inOffset index of <code>in</code> from which to start considering
308
   *          data.
309 310 311 312 313 314 315
   * @param out the ciphertext.
   * @param outOffset index of <code>out</code> from which to store result.
   * @throws IllegalStateException if the instance is not initialised.
   */
  public void update(byte[] in, int inOffset, byte[] out, int outOffset)
  {
    if (wired == null)
316
      throw new IllegalStateException();
317 318 319 320 321 322
    int stageBlockSize, j, i = stages.size();
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
      {
        Stage stage = (Stage) stages.get(it.next());
        stageBlockSize = stage.currentBlockSize();
        for (j = 0; j < blockSize; j += stageBlockSize)
323
          stage.update(in, inOffset + j, out, outOffset + j);
324 325
        i--;
        if (i > 0)
326
          System.arraycopy(out, outOffset, in, inOffset, blockSize);
327 328 329 330 331 332 333 334
      }
  }

  /**
   * Conducts a simple <i>correctness</i> test that consists of basic symmetric
   * encryption / decryption test(s) for all supported block and key sizes of
   * underlying block cipher(s) wrapped by Mode leafs. The test also includes
   * one (1) variable key Known Answer Test (KAT) for each block cipher.
335
   *
336
   * @return <code>true</code> if the implementation passes simple
337
   *         <i>correctness</i> tests. Returns <code>false</code> otherwise.
338 339 340 341 342
   */
  public boolean selfTest()
  {
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
      {
343 344
        if (! ((Stage) stages.get(it.next())).selfTest())
          return false;
345 346 347 348
      }
    return true;
  }
}