summaryrefslogtreecommitdiff
path: root/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java
blob: 685cef5b266561e09d0212f172065ea5d5c17932 (plain)
1
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* Cascade.java --
   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;

/**
 * A <i>Cascade</i> Cipher is the concatenation of two or more block ciphers
 * each with independent keys. Plaintext is input to the first stage; the output
 * 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
 * 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
 * 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:
 * <ol>
 * <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>
 * </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.
   *
   * @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}.
   *
   * @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.
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
   */
  public Object append(Stage stage) throws IllegalArgumentException
  {
    return insert(size(), stage);
  }

  /**
   * Adds to the begining of the current chain, a designated {@link Stage}.
   *
   * @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.
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
   */
  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.
   *
   * @param stage the {@link Stage} to insert into the chain.
   * @return a unique identifier for this stage, within this cascade.
   * @throws IllegalArgumentException if the designated stage is already in the
   *           chain, or it has incompatible characteristics with the current
   *           elements already in the chain.
   * @throws IllegalStateException if the instance is already initialised.
   * @throws IndexOutOfBoundsException if <code>index</code> is less than
   *           <code>0</code> or greater than the current size of this
   *           cascade.
   */
  public Object insert(int index, Stage stage) throws IllegalArgumentException,
      IndexOutOfBoundsException
  {
    if (stages.containsValue(stage))
      throw new IllegalArgumentException();
    if (wired != null || stage == null)
      throw new IllegalStateException();
    if (index < 0 || index > size())
      throw new IndexOutOfBoundsException();
    // check that there is a non-empty set of common block-sizes
    Set set = stage.blockSizes();
    if (stages.isEmpty())
      {
        if (set.isEmpty())
          throw new IllegalArgumentException("1st stage with no block sizes");
      }
    else
      {
        Set common = this.blockSizes();
        common.retainAll(set);
        if (common.isEmpty())
          throw new IllegalArgumentException("no common block sizes found");
      }
    Object result = new Object();
    stageKeys.add(index, result);
    stages.put(result, stage);
    return result;
  }

  /**
   * Returns the current number of stages in this chain.
   *
   * @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}.
   *
   * @return an {@link Iterator} over the stages contained in this instance.
   *         Each element of the returned iterator is a concrete instance of a
   *         {@link Stage}.
   */
  public Iterator stages()
  {
    LinkedList result = new LinkedList();
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
      result.addLast(stages.get(it.next()));
    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}.
   *
   * @return a {@link Set} of supported block sizes common to all the stages of
   *         the chain.
   */
  public Set blockSizes()
  {
    HashSet result = null;
    for (Iterator it = stages.values().iterator(); it.hasNext();)
      {
        Stage aStage = (Stage) it.next();
        if (result == null) // first time
          result = new HashSet(aStage.blockSizes());
        else
          result.retainAll(aStage.blockSizes());
      }
    return result == null ? Collections.EMPTY_SET : result;
  }

  /**
   * Initialises the chain for operation with specific characteristics.
   *
   * @param attributes a set of name-value pairs that describes the desired
   *          future behaviour of this instance.
   * @throws IllegalStateException if the chain, or any of its stages, is
   *           already initialised.
   * @throws InvalidKeyException if the intialisation data provided with the
   *           stage is incorrect or causes an invalid key to be generated.
   * @see Direction#FORWARD
   * @see Direction#REVERSED
   */
  public void init(Map attributes) throws InvalidKeyException
  {
    if (wired != null)
      throw new IllegalStateException();
    Direction flow = (Direction) attributes.get(DIRECTION);
    if (flow == null)
      flow = Direction.FORWARD;
    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()
                                       : lcm(optimalSize,
                                             stage.currentBlockSize());
      }
    if (flow == Direction.REVERSED) // reverse order
      Collections.reverse(stageKeys);
    wired = flow;
    blockSize = optimalSize;
  }

  /**
   * Returns the currently set block size for the chain.
   *
   * @return the current block size for the chain.
   * @throws IllegalStateException if the instance is not initialised.
   */
  public int currentBlockSize()
  {
    if (wired == null)
      throw new IllegalStateException();
    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();)
      ((Stage) stages.get(it.next())).reset();
    if (wired == Direction.REVERSED) // reverse it back
      Collections.reverse(stageKeys);
    wired = null;
    blockSize = 0;
  }

  /**
   * Processes exactly one block of <i>plaintext</i> (if initialised in the
   * {@link Direction#FORWARD} state) or <i>ciphertext</i> (if initialised in
   * the {@link Direction#REVERSED} state).
   *
   * @param in the plaintext.
   * @param inOffset index of <code>in</code> from which to start considering
   *          data.
   * @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)
      throw new IllegalStateException();
    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)
          stage.update(in, inOffset + j, out, outOffset + j);
        i--;
        if (i > 0)
          System.arraycopy(out, outOffset, in, inOffset, blockSize);
      }
  }

  /**
   * 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.
   *
   * @return <code>true</code> if the implementation passes simple
   *         <i>correctness</i> tests. Returns <code>false</code> otherwise.
   */
  public boolean selfTest()
  {
    for (Iterator it = stageKeys.listIterator(); it.hasNext();)
      {
        if (! ((Stage) stages.get(it.next())).selfTest())
          return false;
      }
    return true;
  }
}