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

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