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

   1: /* DHKeyPairPKCS8Codec.java -- PKCS#8 encoder/decoder for DH keys
   2:    Copyright (C) 2006 Free Software Foundation, Inc.
   3: 
   4: This file is 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, or (at your option)
   9: 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; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 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 java.io.ByteArrayOutputStream;
  42: import java.io.IOException;
  43: import java.math.BigInteger;
  44: import java.security.InvalidParameterException;
  45: import java.security.PrivateKey;
  46: import java.security.PublicKey;
  47: import java.util.ArrayList;
  48: 
  49: import gnu.java.security.OID;
  50: import gnu.java.security.Registry;
  51: import gnu.java.security.der.DER;
  52: import gnu.java.security.der.DERReader;
  53: import gnu.java.security.der.DERValue;
  54: import gnu.java.security.der.DERWriter;
  55: import gnu.java.security.key.IKeyPairCodec;
  56: import gnu.java.security.util.DerUtil;
  57: import gnu.java.security.util.Util;
  58: 
  59: public class DHKeyPairPKCS8Codec
  60:     implements IKeyPairCodec
  61: {
  62:   private static final OID DH_ALG_OID = new OID(Registry.DH_OID_STRING);
  63: 
  64:   // implicit 0-arguments constructor
  65: 
  66:   public int getFormatID()
  67:   {
  68:     return PKCS8_FORMAT;
  69:   }
  70: 
  71:   /**
  72:    * @throws InvalidParameterException ALWAYS.
  73:    */
  74:   public byte[] encodePublicKey(PublicKey key)
  75:   {
  76:     throw new InvalidParameterException("Wrong format for public keys");
  77:   }
  78: 
  79:   /**
  80:    * Returns the DER-encoded form of the PKCS#8 ASN.1 <i>PrivateKeyInfo</i>
  81:    * representation of a DH private key. The ASN.1 specification is as follows:
  82:    *
  83:    * <pre>
  84:    *   PrivateKeyInfo ::= SEQUENCE {
  85:    *     version              INTEGER, -- MUST be 0
  86:    *     privateKeyAlgorithm  AlgorithmIdentifier,
  87:    *     privateKey           OCTET STRING
  88:    *   }
  89:    *
  90:    *   AlgorithmIdentifier ::= SEQUENCE {
  91:    *     algorithm   OBJECT IDENTIFIER,
  92:    *     parameters  ANY DEFINED BY algorithm OPTIONAL
  93:    *   }
  94:    *
  95:    *   DhParams ::= SEQUENCE {
  96:    *     p  INTEGER, -- odd prime, p=jq +1
  97:    *     g  INTEGER, -- generator, g
  98:    *     q  INTEGER  -- factor of p-1
  99:    *   }
 100:    * </pre>
 101:    * <p>
 102:    * <b>IMPORTANT</b>: with RI's {@link javax.crypto.spec.DHGenParameterSpec}
 103:    * and {@link javax.crypto.spec.DHParameterSpec} classes, we may end up with
 104:    * Diffie-Hellman keys that have a <code>null</code> for the <code>q</code>
 105:    * parameter. RFC-2631 DOES NOT allow for an <i>optional</i> value for that
 106:    * parameter, hence we replace such null values with <code>0</code>, and do
 107:    * the reverse in the corresponding decode method.
 108:    *
 109:    * @return the DER encoded form of the ASN.1 representation of the
 110:    *         <i>PrivateKeyInfo</i> field in an X.509 certificate.
 111:    * @throw InvalidParameterException if an error occurs during the marshalling
 112:    *        process.
 113:    */
 114:   public byte[] encodePrivateKey(PrivateKey key)
 115:   {
 116:     if (! (key instanceof GnuDHPrivateKey))
 117:       throw new InvalidParameterException("Wrong key type");
 118: 
 119:     DERValue derVersion = new DERValue(DER.INTEGER, BigInteger.ZERO);
 120: 
 121:     DERValue derOID = new DERValue(DER.OBJECT_IDENTIFIER, DH_ALG_OID);
 122: 
 123:     GnuDHPrivateKey pk = (GnuDHPrivateKey) key;
 124:     BigInteger p = pk.getParams().getP();
 125:     BigInteger g = pk.getParams().getG();
 126:     BigInteger q = pk.getQ();
 127:     if (q == null)
 128:       q = BigInteger.ZERO;
 129:     BigInteger x = pk.getX();
 130: 
 131:     ArrayList params = new ArrayList(3);
 132:     params.add(new DERValue(DER.INTEGER, p));
 133:     params.add(new DERValue(DER.INTEGER, g));
 134:     params.add(new DERValue(DER.INTEGER, q));
 135:     DERValue derParams = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, params);
 136: 
 137:     ArrayList algorithmID = new ArrayList(2);
 138:     algorithmID.add(derOID);
 139:     algorithmID.add(derParams);
 140:     DERValue derAlgorithmID = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
 141:                                            algorithmID);
 142: 
 143:     DERValue derPrivateKey = new DERValue(DER.OCTET_STRING, Util.trim(x));
 144: 
 145:     ArrayList pki = new ArrayList(3);
 146:     pki.add(derVersion);
 147:     pki.add(derAlgorithmID);
 148:     pki.add(derPrivateKey);
 149:     DERValue derPKI = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, pki);
 150: 
 151:     byte[] result;
 152:     ByteArrayOutputStream baos = new ByteArrayOutputStream();
 153:     try
 154:       {
 155:         DERWriter.write(baos, derPKI);
 156:         result = baos.toByteArray();
 157:       }
 158:     catch (IOException e)
 159:       {
 160:         InvalidParameterException y = new InvalidParameterException();
 161:         y.initCause(e);
 162:         throw y;
 163:       }
 164: 
 165:     return result;
 166:   }
 167: 
 168:   /**
 169:    * @throws InvalidParameterException ALWAYS.
 170:    */
 171:   public PublicKey decodePublicKey(byte[] input)
 172:   {
 173:     throw new InvalidParameterException("Wrong format for public keys");
 174:   }
 175: 
 176:   /**
 177:    * @param input the byte array to unmarshall into a valid DH
 178:    *          {@link PrivateKey} instance. MUST NOT be null.
 179:    * @return a new instance of a {@link GnuDHPrivateKey} decoded from the
 180:    *         <i>PrivateKeyInfo</i> material fed as <code>input</code>.
 181:    * @throw InvalidParameterException if an exception occurs during the
 182:    *        unmarshalling process.
 183:    */
 184:   public PrivateKey decodePrivateKey(byte[] input)
 185:   {
 186:     if (input == null)
 187:       throw new InvalidParameterException("Input bytes MUST NOT be null");
 188: 
 189:     BigInteger version, p, q, g, x;
 190:     DERReader der = new DERReader(input);
 191:     try
 192:       {
 193:         DERValue derPKI = der.read();
 194:         DerUtil.checkIsConstructed(derPKI, "Wrong PrivateKeyInfo field");
 195: 
 196:         DERValue derVersion = der.read();
 197:         if (! (derVersion.getValue() instanceof BigInteger))
 198:           throw new InvalidParameterException("Wrong Version field");
 199: 
 200:         version = (BigInteger) derVersion.getValue();
 201:         if (version.compareTo(BigInteger.ZERO) != 0)
 202:           throw new InvalidParameterException("Unexpected Version: " + version);
 203: 
 204:         DERValue derAlgoritmID = der.read();
 205:         DerUtil.checkIsConstructed(derAlgoritmID, "Wrong AlgorithmIdentifier field");
 206: 
 207:         DERValue derOID = der.read();
 208:         OID algOID = (OID) derOID.getValue();
 209:         if (! algOID.equals(DH_ALG_OID))
 210:           throw new InvalidParameterException("Unexpected OID: " + algOID);
 211: 
 212:         DERValue derParams = der.read();
 213:         DerUtil.checkIsConstructed(derParams, "Wrong DSS Parameters field");
 214: 
 215:         DERValue val = der.read();
 216:         DerUtil.checkIsBigInteger(val, "Wrong P field");
 217:         p = (BigInteger) val.getValue();
 218:         val = der.read();
 219:         DerUtil.checkIsBigInteger(val, "Wrong G field");
 220:         g = (BigInteger) val.getValue();
 221:         val = der.read();
 222:         DerUtil.checkIsBigInteger(val, "Wrong Q field");
 223:         q = (BigInteger) val.getValue();
 224:         if (q.compareTo(BigInteger.ZERO) == 0)
 225:           q = null;
 226: 
 227:         val = der.read();
 228:         byte[] xBytes = (byte[]) val.getValue();
 229:         x = new BigInteger(1, xBytes);
 230:       }
 231:     catch (IOException e)
 232:       {
 233:         InvalidParameterException y = new InvalidParameterException();
 234:         y.initCause(e);
 235:         throw y;
 236:       }
 237: 
 238:     return new GnuDHPrivateKey(Registry.PKCS8_ENCODING_ID, q, p, g, x);
 239:   }
 240: }