Source for gnu.javax.crypto.cipher.BaseCipher

   1: /* BaseCipher.java --
   2:    Copyright (C) 2001, 2002, 2003, 2006, 2010 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.cipher;
  40: 
  41: import gnu.java.lang.CPStringBuilder;
  42: 
  43: import gnu.java.security.Configuration;
  44: 
  45: import java.security.InvalidKeyException;
  46: import java.util.Arrays;
  47: import java.util.Iterator;
  48: import java.util.Map;
  49: import java.util.logging.Level;
  50: import java.util.logging.Logger;
  51: 
  52: /**
  53:  * A basic abstract class to facilitate implementing symmetric key block
  54:  * ciphers.
  55:  */
  56: public abstract class BaseCipher
  57:     implements IBlockCipher, IBlockCipherSpi
  58: {
  59:   private static final Logger log = Configuration.DEBUG ?
  60:                         Logger.getLogger(BaseCipher.class.getName()) : null;
  61:   /** The canonical name prefix of the cipher. */
  62:   protected String name;
  63:   /** The default block size, in bytes. */
  64:   protected int defaultBlockSize;
  65:   /** The default key size, in bytes. */
  66:   protected int defaultKeySize;
  67:   /** The current block size, in bytes. */
  68:   protected int currentBlockSize;
  69:   /** The session key for this instance. */
  70:   protected transient Object currentKey;
  71:   /** The instance lock. */
  72:   protected Object lock = new Object();
  73: 
  74:   /**
  75:    * Trivial constructor for use by concrete subclasses.
  76:    *
  77:    * @param name the canonical name prefix of this instance.
  78:    * @param defaultBlockSize the default block size in bytes.
  79:    * @param defaultKeySize the default key size in bytes.
  80:    */
  81:   protected BaseCipher(String name, int defaultBlockSize, int defaultKeySize)
  82:   {
  83:     super();
  84: 
  85:     this.name = name;
  86:     this.defaultBlockSize = defaultBlockSize;
  87:     this.defaultKeySize = defaultKeySize;
  88:   }
  89: 
  90:   public abstract Object clone();
  91: 
  92:   public String name()
  93:   {
  94:     CPStringBuilder sb = new CPStringBuilder(name).append('-');
  95:     if (currentKey == null)
  96:       sb.append(String.valueOf(8 * defaultBlockSize));
  97:     else
  98:       sb.append(String.valueOf(8 * currentBlockSize));
  99:     return sb.toString();
 100:   }
 101: 
 102:   public int defaultBlockSize()
 103:   {
 104:     return defaultBlockSize;
 105:   }
 106: 
 107:   public int defaultKeySize()
 108:   {
 109:     return defaultKeySize;
 110:   }
 111: 
 112:   public void init(Map attributes) throws InvalidKeyException
 113:   {
 114:     synchronized (lock)
 115:       {
 116:         if (currentKey != null)
 117:           throw new IllegalStateException();
 118:         Integer bs = (Integer) attributes.get(CIPHER_BLOCK_SIZE);
 119:         if (bs == null) // no block size was specified
 120:           {
 121:             if (currentBlockSize == 0) // happy birthday
 122:               currentBlockSize = defaultBlockSize;
 123:             // else it's a clone. use as is
 124:           }
 125:         else
 126:           {
 127:             currentBlockSize = bs.intValue();
 128:             // ensure that value is valid
 129:             Iterator it;
 130:             boolean ok = false;
 131:             for (it = blockSizes(); it.hasNext();)
 132:               {
 133:                 ok = (currentBlockSize == ((Integer) it.next()).intValue());
 134:                 if (ok)
 135:                   break;
 136:               }
 137:             if (! ok)
 138:               throw new IllegalArgumentException(IBlockCipher.CIPHER_BLOCK_SIZE);
 139:           }
 140:         byte[] k = (byte[]) attributes.get(KEY_MATERIAL);
 141:         currentKey = makeKey(k, currentBlockSize);
 142:       }
 143:   }
 144: 
 145:   public int currentBlockSize()
 146:   {
 147:     if (currentKey == null)
 148:       throw new IllegalStateException();
 149:     return currentBlockSize;
 150:   }
 151: 
 152:   public void reset()
 153:   {
 154:     synchronized (lock)
 155:       {
 156:         currentKey = null;
 157:       }
 158:   }
 159: 
 160:   public void encryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
 161:       throws IllegalStateException
 162:   {
 163:     synchronized (lock)
 164:       {
 165:         if (currentKey == null)
 166:           throw new IllegalStateException();
 167:         encrypt(in, inOffset, out, outOffset, currentKey, currentBlockSize);
 168:       }
 169:   }
 170: 
 171:   public void decryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
 172:       throws IllegalStateException
 173:   {
 174:     synchronized (lock)
 175:       {
 176:         if (currentKey == null)
 177:           throw new IllegalStateException();
 178:         decrypt(in, inOffset, out, outOffset, currentKey, currentBlockSize);
 179:       }
 180:   }
 181: 
 182:   public boolean selfTest()
 183:   {
 184:     int ks;
 185:     Iterator bit;
 186:     // do symmetry tests for all block-size/key-size combos
 187:     for (Iterator kit = keySizes(); kit.hasNext();)
 188:       {
 189:         ks = ((Integer) kit.next()).intValue();
 190:         for (bit = blockSizes(); bit.hasNext();)
 191:           if (! testSymmetry(ks, ((Integer) bit.next()).intValue()))
 192:             return false;
 193:       }
 194:     return true;
 195:   }
 196: 
 197:   private boolean testSymmetry(int ks, int bs)
 198:   {
 199:     try
 200:       {
 201:         byte[] kb = new byte[ks];
 202:         byte[] pt = new byte[bs];
 203:         byte[] ct = new byte[bs];
 204:         byte[] cpt = new byte[bs];
 205:         int i;
 206:         for (i = 0; i < ks; i++)
 207:           kb[i] = (byte) i;
 208:         for (i = 0; i < bs; i++)
 209:           pt[i] = (byte) i;
 210:         Object k = makeKey(kb, bs);
 211:         encrypt(pt, 0, ct, 0, k, bs);
 212:         decrypt(ct, 0, cpt, 0, k, bs);
 213:         return Arrays.equals(pt, cpt);
 214:       }
 215:     catch (Exception x)
 216:       {
 217:         if (Configuration.DEBUG)
 218:           log.log(Level.FINE, "Exception in testSymmetry() for " + name(), x);
 219:         return false;
 220:       }
 221:   }
 222: 
 223:   protected boolean testKat(byte[] kb, byte[] ct)
 224:   {
 225:     return testKat(kb, ct, new byte[ct.length]); // all-zero plaintext
 226:   }
 227: 
 228:   protected boolean testKat(byte[] kb, byte[] ct, byte[] pt)
 229:   {
 230:     try
 231:       {
 232:         int bs = pt.length;
 233:         byte[] t = new byte[bs];
 234:         Object k = makeKey(kb, bs);
 235:         // test encryption
 236:         encrypt(pt, 0, t, 0, k, bs);
 237:         if (! Arrays.equals(t, ct))
 238:           return false;
 239:         // test decryption
 240:         decrypt(t, 0, t, 0, k, bs);
 241:         return Arrays.equals(t, pt);
 242:       }
 243:     catch (Exception x)
 244:       {
 245:         if (Configuration.DEBUG)
 246:           log.log(Level.FINE, "Exception in testKat() for " + name(), x);
 247:         return false;
 248:       }
 249:   }
 250: }