Source for gnu.javax.crypto.mode.BaseMode

   1: /* BaseMode.java --
   2:    Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
   3: 
   4: This file is a part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2 of the License, or (at
   9: your option) any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; if not, write to the Free Software
  18: Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  19: USA
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version.  */
  37: 
  38: 
  39: package gnu.javax.crypto.mode;
  40: 
  41: import gnu.java.lang.CPStringBuilder;
  42: 
  43: import gnu.javax.crypto.cipher.IBlockCipher;
  44: 
  45: import java.security.InvalidKeyException;
  46: import java.util.ArrayList;
  47: import java.util.Arrays;
  48: import java.util.Collections;
  49: import java.util.HashMap;
  50: import java.util.Iterator;
  51: import java.util.Map;
  52: 
  53: /**
  54:  * A basic abstract class to facilitate implementing block cipher modes of
  55:  * operations.
  56:  */
  57: public abstract class BaseMode
  58:     implements IMode
  59: {
  60:   /** The canonical name prefix of this mode. */
  61:   protected String name;
  62:   /** The state indicator of this instance. */
  63:   protected int state;
  64:   /** The underlying block cipher implementation. */
  65:   protected IBlockCipher cipher;
  66:   /** The block size, in bytes, to operate the underlying block cipher in. */
  67:   protected int cipherBlockSize;
  68:   /** The block size, in bytes, in which to operate the mode instance. */
  69:   protected int modeBlockSize;
  70:   /** The initialisation vector value. */
  71:   protected byte[] iv;
  72:   /** The instance lock. */
  73:   protected Object lock = new Object();
  74: 
  75:   /**
  76:    * Trivial constructor for use by concrete subclasses.
  77:    *
  78:    * @param name the canonical name prefix of this mode.
  79:    * @param underlyingCipher the implementation of the underlying cipher.
  80:    * @param cipherBlockSize the block size, in bytes, in which to operate the
  81:    *          underlying cipher.
  82:    */
  83:   protected BaseMode(String name, IBlockCipher underlyingCipher,
  84:                      int cipherBlockSize)
  85:   {
  86:     super();
  87: 
  88:     this.name = name;
  89:     this.cipher = underlyingCipher;
  90:     this.cipherBlockSize = cipherBlockSize;
  91:     state = -1;
  92:   }
  93: 
  94:   public void update(byte[] in, int inOffset, byte[] out, int outOffset)
  95:       throws IllegalStateException
  96:   {
  97:     synchronized (lock)
  98:       {
  99:         switch (state)
 100:           {
 101:           case ENCRYPTION:
 102:             encryptBlock(in, inOffset, out, outOffset);
 103:             break;
 104:           case DECRYPTION:
 105:             decryptBlock(in, inOffset, out, outOffset);
 106:             break;
 107:           default:
 108:             throw new IllegalStateException();
 109:           }
 110:       }
 111:   }
 112: 
 113:   public String name()
 114:   {
 115:     return new CPStringBuilder(name).append('(').append(cipher.name()).append(')')
 116:         .toString();
 117:   }
 118: 
 119:   /**
 120:    * Returns the default value, in bytes, of the mode's block size. This value
 121:    * is part of the construction arguments passed to the Factory methods in
 122:    * {@link ModeFactory}. Unless changed by an invocation of any of the
 123:    * <code>init()</code> methods, a <i>Mode</i> instance would operate with
 124:    * the same block size as its underlying block cipher. As mentioned earlier,
 125:    * the block size of the underlying block cipher itself is specified in one of
 126:    * the method(s) available in the factory class.
 127:    *
 128:    * @return the default value, in bytes, of the mode's block size.
 129:    * @see ModeFactory
 130:    */
 131:   public int defaultBlockSize()
 132:   {
 133:     return cipherBlockSize;
 134:   }
 135: 
 136:   /**
 137:    * Returns the default value, in bytes, of the underlying block cipher key
 138:    * size.
 139:    *
 140:    * @return the default value, in bytes, of the underlying cipher's key size.
 141:    */
 142:   public int defaultKeySize()
 143:   {
 144:     return cipher.defaultKeySize();
 145:   }
 146: 
 147:   /**
 148:    * Returns an {@link Iterator} over the supported block sizes. Each element
 149:    * returned by this object is an {@link Integer}.
 150:    * <p>
 151:    * The default behaviour is to return an iterator with just one value, which
 152:    * is that currently configured for the underlying block cipher. Concrete
 153:    * implementations may override this behaviour to signal their ability to
 154:    * support other values.
 155:    *
 156:    * @return an {@link Iterator} over the supported block sizes.
 157:    */
 158:   public Iterator blockSizes()
 159:   {
 160:     ArrayList al = new ArrayList();
 161:     al.add(Integer.valueOf(cipherBlockSize));
 162:     return Collections.unmodifiableList(al).iterator();
 163:   }
 164: 
 165:   /**
 166:    * Returns an {@link Iterator} over the supported underlying block cipher key
 167:    * sizes. Each element returned by this object is an instance of
 168:    * {@link Integer}.
 169:    *
 170:    * @return an {@link Iterator} over the supported key sizes.
 171:    */
 172:   public Iterator keySizes()
 173:   {
 174:     return cipher.keySizes();
 175:   }
 176: 
 177:   public void init(Map attributes) throws InvalidKeyException,
 178:       IllegalStateException
 179:   {
 180:     synchronized (lock)
 181:       {
 182:         if (state != -1)
 183:           throw new IllegalStateException();
 184:         Integer want = (Integer) attributes.get(STATE);
 185:         if (want != null)
 186:           {
 187:             switch (want.intValue())
 188:               {
 189:               case ENCRYPTION:
 190:                 state = ENCRYPTION;
 191:                 break;
 192:               case DECRYPTION:
 193:                 state = DECRYPTION;
 194:                 break;
 195:               default:
 196:                 throw new IllegalArgumentException();
 197:               }
 198:           }
 199:         Integer bs = (Integer) attributes.get(MODE_BLOCK_SIZE);
 200:         modeBlockSize = (bs == null ? cipherBlockSize : bs.intValue());
 201:         byte[] iv = (byte[]) attributes.get(IV);
 202:         if (iv != null)
 203:           this.iv = (byte[]) iv.clone();
 204:         else
 205:           this.iv = new byte[modeBlockSize];
 206:         cipher.init(attributes);
 207:         setup();
 208:       }
 209:   }
 210: 
 211:   public int currentBlockSize()
 212:   {
 213:     if (state == -1)
 214:       throw new IllegalStateException();
 215:     return modeBlockSize;
 216:   }
 217: 
 218:   public void reset()
 219:   {
 220:     synchronized (lock)
 221:       {
 222:         state = -1;
 223:         iv = null;
 224:         cipher.reset();
 225:         teardown();
 226:       }
 227:   }
 228: 
 229:   public boolean selfTest()
 230:   {
 231:     int ks;
 232:     Iterator bit;
 233:     for (Iterator kit = keySizes(); kit.hasNext();)
 234:       {
 235:         ks = ((Integer) kit.next()).intValue();
 236:         for (bit = blockSizes(); bit.hasNext();)
 237:           if (! testSymmetry(ks, ((Integer) bit.next()).intValue()))
 238:             return false;
 239:       }
 240:     return true;
 241:   }
 242: 
 243:   public abstract Object clone();
 244: 
 245:   /** The initialisation phase of the concrete mode implementation. */
 246:   public abstract void setup();
 247: 
 248:   /** The termination phase of the concrete mode implementation. */
 249:   public abstract void teardown();
 250: 
 251:   public abstract void encryptBlock(byte[] in, int i, byte[] out, int o);
 252: 
 253:   public abstract void decryptBlock(byte[] in, int i, byte[] out, int o);
 254: 
 255:   private boolean testSymmetry(int ks, int bs)
 256:   {
 257:     try
 258:       {
 259:         IMode mode = (IMode) this.clone();
 260:         byte[] iv = new byte[cipherBlockSize]; // all zeroes
 261:         byte[] k = new byte[ks];
 262:         int i;
 263:         for (i = 0; i < ks; i++)
 264:           k[i] = (byte) i;
 265:         int blockCount = 5;
 266:         int limit = blockCount * bs;
 267:         byte[] pt = new byte[limit];
 268:         for (i = 0; i < limit; i++)
 269:           pt[i] = (byte) i;
 270:         byte[] ct = new byte[limit];
 271:         byte[] cpt = new byte[limit];
 272:         Map map = new HashMap();
 273:         map.put(KEY_MATERIAL, k);
 274:         map.put(CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
 275:         map.put(STATE, Integer.valueOf(ENCRYPTION));
 276:         map.put(IV, iv);
 277:         map.put(MODE_BLOCK_SIZE, Integer.valueOf(bs));
 278:         mode.reset();
 279:         mode.init(map);
 280:         for (i = 0; i < blockCount; i++)
 281:           mode.update(pt, i * bs, ct, i * bs);
 282:         mode.reset();
 283:         map.put(STATE, Integer.valueOf(DECRYPTION));
 284:         mode.init(map);
 285:         for (i = 0; i < blockCount; i++)
 286:           mode.update(ct, i * bs, cpt, i * bs);
 287:         return Arrays.equals(pt, cpt);
 288:       }
 289:     catch (Exception x)
 290:       {
 291:         x.printStackTrace(System.err);
 292:         return false;
 293:       }
 294:   }
 295: }