Source for gnu.javax.crypto.key.dh.GnuDHKeyPairGenerator

   1: /* GnuDHKeyPairGenerator.java -- 
   2:    Copyright (C) 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.key.dh;
  40: 
  41: import gnu.java.security.Configuration;
  42: import gnu.java.security.Registry;
  43: import gnu.java.security.hash.Sha160;
  44: import gnu.java.security.key.IKeyPairGenerator;
  45: import gnu.java.security.util.PRNG;
  46: 
  47: import java.math.BigInteger;
  48: import java.security.KeyPair;
  49: import java.security.PrivateKey;
  50: import java.security.PublicKey;
  51: import java.security.SecureRandom;
  52: import java.util.Map;
  53: import java.util.logging.Logger;
  54: 
  55: import javax.crypto.spec.DHGenParameterSpec;
  56: import javax.crypto.spec.DHParameterSpec;
  57: 
  58: /**
  59:  * An implementation of a Diffie-Hellman keypair generator.
  60:  * <p>
  61:  * Reference:
  62:  * <ol>
  63:  * <li><a href="http://www.ietf.org/rfc/rfc2631.txt">Diffie-Hellman Key
  64:  * Agreement Method</a><br>
  65:  * Eric Rescorla.</li>
  66:  * </ol>
  67:  */
  68: public class GnuDHKeyPairGenerator
  69:     implements IKeyPairGenerator
  70: {
  71:   private static final Logger log = Logger.getLogger(GnuDHKeyPairGenerator.class.getName());
  72:   /**
  73:    * Property name of an optional {@link SecureRandom} instance to use. The
  74:    * default is to use a classloader singleton from {@link PRNG}.
  75:    */
  76:   public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.dh.prng";
  77:   /**
  78:    * Property name of an optional {@link DHGenParameterSpec} or
  79:    * {@link DHParameterSpec} instance to use for this generator.
  80:    */
  81:   public static final String DH_PARAMETERS = "gnu.crypto.dh.params";
  82:   /** Property name of the size in bits (Integer) of the public prime (p). */
  83:   public static final String PRIME_SIZE = "gnu.crypto.dh.L";
  84:   /** Property name of the size in bits (Integer) of the private exponent (x). */
  85:   public static final String EXPONENT_SIZE = "gnu.crypto.dh.m";
  86:   /**
  87:    * Property name of the preferred encoding format to use when externalizing
  88:    * generated instance of key-pairs from this generator. The property is taken
  89:    * to be an {@link Integer} that encapsulates an encoding format identifier.
  90:    */
  91:   public static final String PREFERRED_ENCODING_FORMAT = "gnu.crypto.dh.encoding";
  92:   /** Default value for the size in bits of the public prime (p). */
  93:   public static final int DEFAULT_PRIME_SIZE = 512;
  94:   /** Default value for the size in bits of the private exponent (x). */
  95:   public static final int DEFAULT_EXPONENT_SIZE = 160;
  96:   /** Default encoding format to use when none was specified. */
  97:   private static final int DEFAULT_ENCODING_FORMAT = Registry.RAW_ENCODING_ID;
  98:   /** The SHA instance to use. */
  99:   private Sha160 sha = new Sha160();
 100:   /** The optional {@link SecureRandom} instance to use. */
 101:   private SecureRandom rnd = null;
 102:   /** The desired size in bits of the public prime (p). */
 103:   private int l;
 104:   /** The desired size in bits of the private exponent (x). */
 105:   private int m;
 106:   private BigInteger seed;
 107:   private BigInteger counter;
 108:   private BigInteger q;
 109:   private BigInteger p;
 110:   private BigInteger j;
 111:   private BigInteger g;
 112:   /** Our default source of randomness. */
 113:   private PRNG prng = null;
 114:   /** Preferred encoding format of generated keys. */
 115:   private int preferredFormat;
 116: 
 117:   // default 0-arguments constructor
 118: 
 119:   public String name()
 120:   {
 121:     return Registry.DH_KPG;
 122:   }
 123: 
 124:   public void setup(Map attributes)
 125:   {
 126:     // do we have a SecureRandom, or should we use our own?
 127:     rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
 128:     // are we given a set of Diffie-Hellman generation parameters or we shall
 129:     // use our own?
 130:     Object params = attributes.get(DH_PARAMETERS);
 131:     // find out the desired sizes
 132:     if (params instanceof DHGenParameterSpec)
 133:       {
 134:         DHGenParameterSpec jceSpec = (DHGenParameterSpec) params;
 135:         l = jceSpec.getPrimeSize();
 136:         m = jceSpec.getExponentSize();
 137:       }
 138:     else if (params instanceof DHParameterSpec)
 139:       {
 140:         // FIXME: I'm not sure this is correct. It seems to behave the
 141:         // same way as Sun's RI, but I don't know if this behavior is
 142:         // documented anywhere.
 143:         DHParameterSpec jceSpec = (DHParameterSpec) params;
 144:         p = jceSpec.getP();
 145:         g = jceSpec.getG();
 146:         l = p.bitLength();
 147:         m = jceSpec.getL();
 148:         // If no exponent size was given, generate an exponent as
 149:         // large as the prime.
 150:         if (m == 0)
 151:           m = l;
 152:       }
 153:     else
 154:       {
 155:         Integer bi = (Integer) attributes.get(PRIME_SIZE);
 156:         l = (bi == null ? DEFAULT_PRIME_SIZE : bi.intValue());
 157:         bi = (Integer) attributes.get(EXPONENT_SIZE);
 158:         m = (bi == null ? DEFAULT_EXPONENT_SIZE : bi.intValue());
 159:       }
 160:     if ((l % 256) != 0 || l < DEFAULT_PRIME_SIZE)
 161:       throw new IllegalArgumentException("invalid modulus size");
 162:     if ((m % 8) != 0 || m < DEFAULT_EXPONENT_SIZE)
 163:       throw new IllegalArgumentException("invalid exponent size");
 164:     if (m > l)
 165:       throw new IllegalArgumentException("exponent size > modulus size");
 166:     // what is the preferred encoding format
 167:     Integer formatID = (Integer) attributes.get(PREFERRED_ENCODING_FORMAT);
 168:     preferredFormat = formatID == null ? DEFAULT_ENCODING_FORMAT
 169:                                        : formatID.intValue();
 170:   }
 171: 
 172:   public KeyPair generate()
 173:   {
 174:     if (p == null)
 175:       {
 176:         BigInteger[] params = new RFC2631(m, l, rnd).generateParameters();
 177:         seed = params[RFC2631.DH_PARAMS_SEED];
 178:         counter = params[RFC2631.DH_PARAMS_COUNTER];
 179:         q = params[RFC2631.DH_PARAMS_Q];
 180:         p = params[RFC2631.DH_PARAMS_P];
 181:         j = params[RFC2631.DH_PARAMS_J];
 182:         g = params[RFC2631.DH_PARAMS_G];
 183:         if (Configuration.DEBUG)
 184:           {
 185:             log.fine("seed: 0x" + seed.toString(16));
 186:             log.fine("counter: " + counter.intValue());
 187:             log.fine("q: 0x" + q.toString(16));
 188:             log.fine("p: 0x" + p.toString(16));
 189:             log.fine("j: 0x" + j.toString(16));
 190:             log.fine("g: 0x" + g.toString(16));
 191:           }
 192:       }
 193:     // generate a private number x of length m such as: 1 < x < q - 1
 194:     BigInteger q_minus_1 = null;
 195:     if (q != null)
 196:       q_minus_1 = q.subtract(BigInteger.ONE);
 197:     // We already check if m is modulo 8 in `setup.' This could just
 198:     // be m >>> 3.
 199:     byte[] mag = new byte[(m + 7) / 8];
 200:     BigInteger x;
 201:     while (true)
 202:       {
 203:         nextRandomBytes(mag);
 204:         x = new BigInteger(1, mag);
 205:         if (x.bitLength() == m && x.compareTo(BigInteger.ONE) > 0
 206:             && (q_minus_1 == null || x.compareTo(q_minus_1) < 0))
 207:           break;
 208:       }
 209:     BigInteger y = g.modPow(x, p);
 210:     PrivateKey secK = new GnuDHPrivateKey(preferredFormat, q, p, g, x);
 211:     PublicKey pubK = new GnuDHPublicKey(preferredFormat, q, p, g, y);
 212:     return new KeyPair(pubK, secK);
 213:   }
 214: 
 215:   /**
 216:    * Fills the designated byte array with random data.
 217:    * 
 218:    * @param buffer the byte array to fill with random data.
 219:    */
 220:   private void nextRandomBytes(byte[] buffer)
 221:   {
 222:     if (rnd != null)
 223:       rnd.nextBytes(buffer);
 224:     else
 225:       getDefaultPRNG().nextBytes(buffer);
 226:   }
 227: 
 228:   private PRNG getDefaultPRNG()
 229:   {
 230:     if (prng == null)
 231:       prng = PRNG.getInstance();
 232: 
 233:     return prng;
 234:   }
 235: }