Source for gnu.javax.crypto.jce.prng.ICMRandomSpi

   1: /* ICMRandomSpi.java -- 
   2:    Copyright (C) 2001, 2002, 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.jce.prng;
  40: 
  41: import gnu.java.security.Configuration;
  42: import gnu.java.security.Registry;
  43: import gnu.java.security.prng.LimitReachedException;
  44: import gnu.javax.crypto.cipher.IBlockCipher;
  45: import gnu.javax.crypto.prng.ICMGenerator;
  46: 
  47: import java.math.BigInteger;
  48: import java.security.SecureRandomSpi;
  49: import java.util.HashMap;
  50: import java.util.Random;
  51: import java.util.logging.Logger;
  52: 
  53: /**
  54:  * An <em>Adapter</em> class around {@link ICMGenerator} to allow using this
  55:  * algorithm as a JCE {@link java.security.SecureRandom}.
  56:  */
  57: public class ICMRandomSpi
  58:     extends SecureRandomSpi
  59: {
  60:   private static final Logger log = Logger.getLogger(ICMRandomSpi.class.getName());
  61:   /** Class-wide prng to generate random material for the underlying prng. */
  62:   private static final ICMGenerator prng; // blank final
  63:   static
  64:     {
  65:       prng = new ICMGenerator();
  66:       resetLocalPRNG();
  67:     }
  68: 
  69:   // error messages
  70:   private static final String MSG = "Exception while setting up an "
  71:                                     + Registry.ICM_PRNG + " SPI: ";
  72:   private static final String RETRY = "Retry...";
  73:   private static final String LIMIT_REACHED_MSG = "Limit reached: ";
  74:   private static final String RESEED = "Re-seed...";
  75:   /** Our underlying prng instance. */
  76:   private ICMGenerator adaptee = new ICMGenerator();
  77: 
  78:   // default 0-arguments constructor
  79: 
  80:   private static void resetLocalPRNG()
  81:   {
  82:     if (Configuration.DEBUG)
  83:       log.entering(ICMRandomSpi.class.getName(), "resetLocalPRNG");
  84:     HashMap attributes = new HashMap();
  85:     attributes.put(ICMGenerator.CIPHER, Registry.AES_CIPHER);
  86:     byte[] key = new byte[128 / 8]; // AES default key size
  87:     Random rand = new Random(System.currentTimeMillis());
  88:     rand.nextBytes(key);
  89:     attributes.put(IBlockCipher.KEY_MATERIAL, key);
  90:     int aesBlockSize = 128 / 8; // AES block size in bytes
  91:     byte[] offset = new byte[aesBlockSize];
  92:     rand.nextBytes(offset);
  93:     attributes.put(ICMGenerator.OFFSET, offset);
  94:     int ndxLen = 0; // the segment length
  95:     // choose a random value between 1 and aesBlockSize / 2
  96:     int limit = aesBlockSize / 2;
  97:     while (ndxLen < 1 || ndxLen > limit)
  98:       ndxLen = rand.nextInt(limit + 1);
  99:     attributes.put(ICMGenerator.SEGMENT_INDEX_LENGTH, Integer.valueOf(ndxLen));
 100:     byte[] index = new byte[ndxLen];
 101:     rand.nextBytes(index);
 102:     attributes.put(ICMGenerator.SEGMENT_INDEX, new BigInteger(1, index));
 103:     prng.setup(attributes);
 104:     if (Configuration.DEBUG)
 105:       log.exiting(ICMRandomSpi.class.getName(), "resetLocalPRNG");
 106:   }
 107: 
 108:   public byte[] engineGenerateSeed(int numBytes)
 109:   {
 110:     if (Configuration.DEBUG)
 111:       log.entering(this.getClass().getName(), "engineGenerateSeed");
 112:     if (numBytes < 1)
 113:       {
 114:         if (Configuration.DEBUG)
 115:           log.exiting(this.getClass().getName(), "engineGenerateSeed");
 116:         return new byte[0];
 117:       }
 118:     byte[] result = new byte[numBytes];
 119:     this.engineNextBytes(result);
 120:     if (Configuration.DEBUG)
 121:       log.exiting(this.getClass().getName(), "engineGenerateSeed");
 122:     return result;
 123:   }
 124: 
 125:   public void engineNextBytes(byte[] bytes)
 126:   {
 127:     if (Configuration.DEBUG)
 128:       log.entering(this.getClass().getName(), "engineNextBytes");
 129:     if (! adaptee.isInitialised())
 130:       this.engineSetSeed(new byte[0]);
 131:     while (true)
 132:       {
 133:         try
 134:           {
 135:             adaptee.nextBytes(bytes, 0, bytes.length);
 136:             break;
 137:           }
 138:         catch (LimitReachedException x)
 139:           { // reseed the generator
 140:             if (Configuration.DEBUG)
 141:               {
 142:                 log.fine(LIMIT_REACHED_MSG + String.valueOf(x));
 143:                 log.fine(RESEED);
 144:               }
 145:             resetLocalPRNG();
 146:           }
 147:       }
 148:     if (Configuration.DEBUG)
 149:       log.exiting(this.getClass().getName(), "engineNextBytes");
 150:   }
 151: 
 152:   public void engineSetSeed(byte[] seed)
 153:   {
 154:     if (Configuration.DEBUG)
 155:       log.entering(this.getClass().getName(), "engineSetSeed");
 156:     // compute the total number of random bytes required to setup adaptee
 157:     int materialLength = 0;
 158:     materialLength += 16; // key material size
 159:     materialLength += 16; // offset size
 160:     materialLength += 8; // index size == half of an AES block
 161:     byte[] material = new byte[materialLength];
 162:     // use as much as possible bytes from the seed
 163:     int materialOffset = 0;
 164:     int materialLeft = material.length;
 165:     if (seed.length > 0)
 166:       { // copy some bytes into key and update indices
 167:         int lenToCopy = Math.min(materialLength, seed.length);
 168:         System.arraycopy(seed, 0, material, 0, lenToCopy);
 169:         materialOffset += lenToCopy;
 170:         materialLeft -= lenToCopy;
 171:       }
 172:     if (materialOffset > 0) // generate the rest
 173:       {
 174:         while (true)
 175:           {
 176:             try
 177:               {
 178:                 prng.nextBytes(material, materialOffset, materialLeft);
 179:                 break;
 180:               }
 181:             catch (IllegalStateException x)
 182:               { // should not happen
 183:                 throw new InternalError(MSG + String.valueOf(x));
 184:               }
 185:             catch (LimitReachedException x)
 186:               {
 187:                 if (Configuration.DEBUG)
 188:                   {
 189:                     log.fine(MSG + String.valueOf(x));
 190:                     log.fine(RETRY);
 191:                   }
 192:               }
 193:           }
 194:       }
 195:     // setup the underlying adaptee instance
 196:     HashMap attributes = new HashMap();
 197:     // use AES cipher with 128-bit block size
 198:     attributes.put(ICMGenerator.CIPHER, Registry.AES_CIPHER);
 199:     // use an index the size of quarter of an AES block
 200:     attributes.put(ICMGenerator.SEGMENT_INDEX_LENGTH, Integer.valueOf(4));
 201:     // specify the key
 202:     byte[] key = new byte[16];
 203:     System.arraycopy(material, 0, key, 0, 16);
 204:     attributes.put(IBlockCipher.KEY_MATERIAL, key);
 205:     // specify the offset
 206:     byte[] offset = new byte[16];
 207:     System.arraycopy(material, 16, offset, 0, 16);
 208:     attributes.put(ICMGenerator.OFFSET, offset);
 209:     // specify the index
 210:     byte[] index = new byte[8];
 211:     System.arraycopy(material, 32, index, 0, 8);
 212:     attributes.put(ICMGenerator.SEGMENT_INDEX, new BigInteger(1, index));
 213:     adaptee.init(attributes);
 214:     if (Configuration.DEBUG)
 215:       log.exiting(this.getClass().getName(), "engineSetSeed");
 216:   }
 217: }