Source for gnu.java.security.key.rsa.RSAKeyPairPKCS8Codec

   1: /* RSAKeyPairPKCS8Codec.java -- PKCS#8 Encoding/Decoding handler
   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.java.security.key.rsa;
  40: 
  41: import gnu.java.security.Configuration;
  42: import gnu.java.security.OID;
  43: import gnu.java.security.Registry;
  44: import gnu.java.security.der.DER;
  45: import gnu.java.security.der.DERReader;
  46: import gnu.java.security.der.DERValue;
  47: import gnu.java.security.der.DERWriter;
  48: import gnu.java.security.key.IKeyPairCodec;
  49: import gnu.java.security.util.DerUtil;
  50: 
  51: import java.io.ByteArrayOutputStream;
  52: import java.io.IOException;
  53: import java.math.BigInteger;
  54: import java.security.InvalidParameterException;
  55: import java.security.PrivateKey;
  56: import java.security.PublicKey;
  57: import java.util.ArrayList;
  58: import java.util.logging.Logger;
  59: 
  60: /**
  61:  * An implementation of an {@link IKeyPairCodec} that knows how to encode /
  62:  * decode PKCS#8 ASN.1 external representation of RSA private keys.
  63:  */
  64: public class RSAKeyPairPKCS8Codec
  65:     implements IKeyPairCodec
  66: {
  67:   private static final Logger log = Logger.getLogger(RSAKeyPairPKCS8Codec.class.getName());
  68:   private static final OID RSA_ALG_OID = new OID(Registry.RSA_OID_STRING);
  69: 
  70:   // implicit 0-arguments constructor
  71: 
  72:   public int getFormatID()
  73:   {
  74:     return PKCS8_FORMAT;
  75:   }
  76: 
  77:   /**
  78:    * @throws InvalidParameterException ALWAYS.
  79:    */
  80:   public byte[] encodePublicKey(PublicKey key)
  81:   {
  82:     throw new InvalidParameterException("Wrong format for public keys");
  83:   }
  84: 
  85:   /**
  86:    * Returns the PKCS#8 ASN.1 <i>PrivateKeyInfo</i> representation of an RSA
  87:    * private key. The ASN.1 specification is as follows:
  88:    * <pre>
  89:    *   PrivateKeyInfo ::= SEQUENCE {
  90:    *     version              INTEGER, -- MUST be 0
  91:    *     privateKeyAlgorithm  AlgorithmIdentifier,
  92:    *     privateKey           OCTET STRING
  93:    *   }
  94:    *
  95:    *   AlgorithmIdentifier ::= SEQUENCE {
  96:    *     algorithm   OBJECT IDENTIFIER,
  97:    *     parameters  ANY DEFINED BY algorithm OPTIONAL
  98:    *   }
  99:    * </pre>
 100:    * <p>
 101:    * As indicated in RFC-2459: "The parameters field shall have ASN.1 type NULL
 102:    * for this algorithm identifier.".
 103:    * <p>
 104:    * The <i>privateKey</i> field, which is an OCTET STRING, contains the
 105:    * DER-encoded form of the RSA private key defined as:
 106:    * <pre>
 107:    *   RSAPrivateKey ::= SEQUENCE {
 108:    *     version                 INTEGER, -- MUST be 0
 109:    *     modulus                 INTEGER, -- n
 110:    *     publicExponent          INTEGER, -- e
 111:    *     privateExponent         INTEGER, -- d
 112:    *     prime1                  INTEGER, -- p
 113:    *     prime2                  INTEGER, -- q
 114:    *     exponent1               INTEGER, -- d mod (p-1)
 115:    *     exponent2               INTEGER, -- d mod (q-1)
 116:    *     coefficient             INTEGER, -- (inverse of q) mod p
 117:    *   }
 118:    * </pre>
 119:    * 
 120:    * @return the DER encoded form of the ASN.1 representation of the
 121:    *         <i>PrivateKeyInfo</i> field for an RSA {@link PrivateKey}..
 122:    * @throw InvalidParameterException if an error occurs during the marshalling
 123:    *        process.
 124:    */
 125:   public byte[] encodePrivateKey(PrivateKey key)
 126:   {
 127:     if (Configuration.DEBUG)
 128:       log.entering(this.getClass().getName(), "encodePrivateKey()", key);
 129:     if (! (key instanceof GnuRSAPrivateKey))
 130:       throw new InvalidParameterException("Wrong key type");
 131: 
 132:     GnuRSAPrivateKey pk = (GnuRSAPrivateKey) key;
 133:     BigInteger n = pk.getN();
 134:     BigInteger e = pk.getE();
 135:     BigInteger d = pk.getPrivateExponent();
 136:     BigInteger p = pk.getPrimeP();
 137:     BigInteger q = pk.getPrimeQ();
 138:     BigInteger dP = pk.getPrimeExponentP();
 139:     BigInteger dQ = pk.getPrimeExponentQ();
 140:     BigInteger qInv = pk.getCrtCoefficient();
 141: 
 142:     DERValue derVersion = new DERValue(DER.INTEGER, BigInteger.ZERO);
 143: 
 144:     DERValue derOID = new DERValue(DER.OBJECT_IDENTIFIER, RSA_ALG_OID);
 145: 
 146:     ArrayList algorithmID = new ArrayList(2);
 147:     algorithmID.add(derOID);
 148:     algorithmID.add(new DERValue(DER.NULL, null));
 149:     DERValue derAlgorithmID = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
 150:                                            algorithmID);
 151: 
 152:     DERValue derRSAVersion = new DERValue(DER.INTEGER, BigInteger.ZERO);
 153:     DERValue derN = new DERValue(DER.INTEGER, n);
 154:     DERValue derE = new DERValue(DER.INTEGER, e);
 155:     DERValue derD = new DERValue(DER.INTEGER, d);
 156:     DERValue derP = new DERValue(DER.INTEGER, p);
 157:     DERValue derQ = new DERValue(DER.INTEGER, q);
 158:     DERValue derDP = new DERValue(DER.INTEGER, dP);
 159:     DERValue derDQ = new DERValue(DER.INTEGER, dQ);
 160:     DERValue derQInv = new DERValue(DER.INTEGER, qInv);
 161: 
 162:     ArrayList rsaPrivateKey = new ArrayList();
 163:     rsaPrivateKey.add(derRSAVersion);
 164:     rsaPrivateKey.add(derN);
 165:     rsaPrivateKey.add(derE);
 166:     rsaPrivateKey.add(derD);
 167:     rsaPrivateKey.add(derP);
 168:     rsaPrivateKey.add(derQ);
 169:     rsaPrivateKey.add(derDP);
 170:     rsaPrivateKey.add(derDQ);
 171:     rsaPrivateKey.add(derQInv);
 172:     DERValue derRSAPrivateKey = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
 173:                                              rsaPrivateKey);
 174:     byte[] pkBytes = derRSAPrivateKey.getEncoded();
 175:     DERValue derPrivateKey = new DERValue(DER.OCTET_STRING, pkBytes);
 176: 
 177:     ArrayList pki = new ArrayList(3);
 178:     pki.add(derVersion);
 179:     pki.add(derAlgorithmID);
 180:     pki.add(derPrivateKey);
 181:     DERValue derPKI = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, pki);
 182: 
 183:     byte[] result;
 184:     ByteArrayOutputStream baos = new ByteArrayOutputStream();
 185:     try
 186:       {
 187:         DERWriter.write(baos, derPKI);
 188:         result = baos.toByteArray();
 189:       }
 190:     catch (IOException x)
 191:       {
 192:         InvalidParameterException y = new InvalidParameterException();
 193:         y.initCause(x);
 194:         throw y;
 195:       }
 196:     if (Configuration.DEBUG)
 197:       log.exiting(this.getClass().getName(), "encodePrivateKey()", result);
 198:     return result;
 199:   }
 200: 
 201:   /**
 202:    * @throws InvalidParameterException ALWAYS.
 203:    */
 204:   public PublicKey decodePublicKey(byte[] input)
 205:   {
 206:     throw new InvalidParameterException("Wrong format for public keys");
 207:   }
 208: 
 209:   /**
 210:    * @param input the byte array to unmarshall into a valid RSA
 211:    *          {@link PrivateKey} instance. MUST NOT be null.
 212:    * @return a new instance of a {@link GnuRSAPrivateKey} decoded from the
 213:    *         <i>PrivateKeyInfo</i> material fed as <code>input</code>.
 214:    * @throw InvalidParameterException if an exception occurs during the
 215:    *        unmarshalling process.
 216:    */
 217:   public PrivateKey decodePrivateKey(byte[] input)
 218:   {
 219:     if (Configuration.DEBUG)
 220:       log.entering(this.getClass().getName(), "decodePrivateKey()", input);
 221:     if (input == null)
 222:       throw new InvalidParameterException("Input bytes MUST NOT be null");
 223: 
 224:     BigInteger version, n, e, d, p, q, dP, dQ, qInv;
 225:     DERReader der = new DERReader(input);
 226:     try
 227:       {
 228:         DERValue derPKI = der.read();
 229:         DerUtil.checkIsConstructed(derPKI, "Wrong PrivateKeyInfo field");
 230: 
 231:         DERValue derVersion = der.read();
 232:         DerUtil.checkIsBigInteger(derVersion, "Wrong Version field");
 233:         version = (BigInteger) derVersion.getValue();
 234:         if (version.compareTo(BigInteger.ZERO) != 0)
 235:           throw new InvalidParameterException("Unexpected Version: " + version);
 236: 
 237:         DERValue derAlgoritmID = der.read();
 238:         DerUtil.checkIsConstructed(derAlgoritmID, "Wrong AlgorithmIdentifier field");
 239: 
 240:         DERValue derOID = der.read();
 241:         OID algOID = (OID) derOID.getValue();
 242:         if (! algOID.equals(RSA_ALG_OID))
 243:           throw new InvalidParameterException("Unexpected OID: " + algOID);
 244: 
 245:         // rfc-2459 states that this field is OPTIONAL but NULL if/when present
 246:         DERValue val = der.read();
 247:         if (val.getTag() == DER.NULL)
 248:           val = der.read();
 249: 
 250:         byte[] pkBytes = (byte[]) val.getValue();
 251:         der = new DERReader(pkBytes);
 252:         DERValue derRSAPrivateKey = der.read();
 253:         DerUtil.checkIsConstructed(derRSAPrivateKey, "Wrong RSAPrivateKey field");
 254:         
 255:         val = der.read();
 256:         DerUtil.checkIsBigInteger(val, "Wrong RSAPrivateKey Version field");
 257:         version = (BigInteger) val.getValue();
 258:         if (version.compareTo(BigInteger.ZERO) != 0)
 259:           throw new InvalidParameterException("Unexpected RSAPrivateKey Version: "
 260:                                               + version);
 261: 
 262:         val = der.read();
 263:         DerUtil.checkIsBigInteger(val, "Wrong modulus field");
 264:         n = (BigInteger) val.getValue();
 265:         val = der.read();
 266:         DerUtil.checkIsBigInteger(val, "Wrong publicExponent field");
 267:         e = (BigInteger) val.getValue();
 268:         val = der.read();
 269:         DerUtil.checkIsBigInteger(val, "Wrong privateExponent field");
 270:         d = (BigInteger) val.getValue();
 271:         val = der.read();
 272:         DerUtil.checkIsBigInteger(val, "Wrong prime1 field");
 273:         p = (BigInteger) val.getValue();
 274:         val = der.read();
 275:         DerUtil.checkIsBigInteger(val, "Wrong prime2 field");
 276:         q = (BigInteger) val.getValue();
 277:         val = der.read();
 278:         DerUtil.checkIsBigInteger(val, "Wrong exponent1 field");
 279:         dP = (BigInteger) val.getValue();
 280:         val = der.read();
 281:         DerUtil.checkIsBigInteger(val, "Wrong exponent2 field");
 282:         dQ = (BigInteger) val.getValue();
 283:         val = der.read();
 284:         DerUtil.checkIsBigInteger(val, "Wrong coefficient field");
 285:         qInv = (BigInteger) val.getValue();
 286:       }
 287:     catch (IOException x)
 288:       {
 289:         InvalidParameterException y = new InvalidParameterException();
 290:         y.initCause(x);
 291:         throw y;
 292:       }
 293:     PrivateKey result = new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
 294:                                              n, e, d, p, q, dP, dQ, qInv);
 295:     if (Configuration.DEBUG)
 296:       log.exiting(this.getClass().getName(), "decodePrivateKey()", result);
 297:     return result;
 298:   }
 299: }