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

   1: /* RSAKeyPairX509Codec.java -- X.509 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.BitString;
  45: import gnu.java.security.der.DER;
  46: import gnu.java.security.der.DERReader;
  47: import gnu.java.security.der.DERValue;
  48: import gnu.java.security.der.DERWriter;
  49: import gnu.java.security.key.IKeyPairCodec;
  50: import gnu.java.security.util.DerUtil;
  51: 
  52: import java.io.ByteArrayOutputStream;
  53: import java.io.IOException;
  54: import java.math.BigInteger;
  55: import java.security.InvalidParameterException;
  56: import java.security.PrivateKey;
  57: import java.security.PublicKey;
  58: import java.util.ArrayList;
  59: import java.util.logging.Logger;
  60: 
  61: /**
  62:  * An implementation of an {@link IKeyPairCodec} that knows how to encode /
  63:  * decode X.509 ASN.1 external representation of RSA public keys.
  64:  */
  65: public class RSAKeyPairX509Codec
  66:     implements IKeyPairCodec
  67: {
  68:   private static final Logger log = Logger.getLogger(RSAKeyPairX509Codec.class.getName());
  69:   private static final OID RSA_ALG_OID = new OID(Registry.RSA_OID_STRING);
  70: 
  71:   // implicit 0-arguments constructor
  72: 
  73:   public int getFormatID()
  74:   {
  75:     return X509_FORMAT;
  76:   }
  77: 
  78:   /**
  79:    * Returns the X.509 ASN.1 <i>SubjectPublicKeyInfo</i> representation of an
  80:    * RSA public key. The ASN.1 specification, as defined in RFC-3280, and
  81:    * RFC-2459, is as follows:
  82:    *
  83:    * <pre>
  84:    *   SubjectPublicKeyInfo ::= SEQUENCE {
  85:    *     algorithm         AlgorithmIdentifier,
  86:    *     subjectPublicKey  BIT STRING
  87:    *   }
  88:    *
  89:    *   AlgorithmIdentifier ::= SEQUENCE {
  90:    *     algorithm   OBJECT IDENTIFIER,
  91:    *     parameters  ANY DEFINED BY algorithm OPTIONAL
  92:    *   }
  93:    * </pre>
  94:    * <p>
  95:    * As indicated in RFC-2459: "The parameters field shall have ASN.1 type NULL
  96:    * for this algorithm identifier.".
  97:    * <p>
  98:    * The <i>subjectPublicKey</i> field, which is a BIT STRING, contains the
  99:    * DER-encoded form of the RSA public key defined as:
 100:    *
 101:    * <pre>
 102:    *   RSAPublicKey ::= SEQUENCE {
 103:    *     modulus         INTEGER, -- n
 104:    *     publicExponent  INTEGER  -- e
 105:    *   }
 106:    * </pre>
 107:    *
 108:    * @param key the {@link PublicKey} instance to encode. MUST be an instance of
 109:    *          {@link GnuRSAPublicKey}.
 110:    * @return the ASN.1 representation of the <i>SubjectPublicKeyInfo</i> in an
 111:    *         X.509 certificate.
 112:    * @throw InvalidParameterException if <code>key</code> is not an instance
 113:    *        of {@link GnuRSAPublicKey} or if an exception occurs during the
 114:    *        marshalling process.
 115:    */
 116:   public byte[] encodePublicKey(PublicKey key)
 117:   {
 118:     if (Configuration.DEBUG)
 119:       log.entering(this.getClass().getName(), "encodePublicKey()", key);
 120:     if (! (key instanceof GnuRSAPublicKey))
 121:       throw new InvalidParameterException("key");
 122: 
 123:     DERValue derOID = new DERValue(DER.OBJECT_IDENTIFIER, RSA_ALG_OID);
 124: 
 125:     GnuRSAPublicKey rsaKey = (GnuRSAPublicKey) key;
 126:     BigInteger n = rsaKey.getN();
 127:     BigInteger e = rsaKey.getE();
 128: 
 129:     DERValue derN = new DERValue(DER.INTEGER, n);
 130:     DERValue derE = new DERValue(DER.INTEGER, e);
 131: 
 132:     ArrayList algorithmID = new ArrayList(2);
 133:     algorithmID.add(derOID);
 134:     algorithmID.add(new DERValue(DER.NULL, null));
 135:     DERValue derAlgorithmID = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
 136:                                            algorithmID);
 137: 
 138:     ArrayList publicKey = new ArrayList(2);
 139:     publicKey.add(derN);
 140:     publicKey.add(derE);
 141:     DERValue derPublicKey = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
 142:                                          publicKey);
 143:     byte[] spkBytes = derPublicKey.getEncoded();
 144:     DERValue derSPK = new DERValue(DER.BIT_STRING, new BitString(spkBytes));
 145: 
 146:     ArrayList spki = new ArrayList(2);
 147:     spki.add(derAlgorithmID);
 148:     spki.add(derSPK);
 149:     DERValue derSPKI = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, spki);
 150: 
 151:     byte[] result;
 152:     ByteArrayOutputStream baos = new ByteArrayOutputStream();
 153:     try
 154:       {
 155:         DERWriter.write(baos, derSPKI);
 156:         result = baos.toByteArray();
 157:       }
 158:     catch (IOException x)
 159:       {
 160:         InvalidParameterException y = new InvalidParameterException(x.getMessage());
 161:         y.initCause(x);
 162:         throw y;
 163:       }
 164:     if (Configuration.DEBUG)
 165:       log.exiting(this.getClass().getName(), "encodePublicKey()", result);
 166:     return result;
 167:   }
 168: 
 169:   /**
 170:    * @throws InvalidParameterException ALWAYS.
 171:    */
 172:   public byte[] encodePrivateKey(PrivateKey key)
 173:   {
 174:     throw new InvalidParameterException("Wrong format for private keys");
 175:   }
 176: 
 177:   /**
 178:    * @param input the byte array to unmarshall into a valid RSA
 179:    *          {@link PublicKey} instance. MUST NOT be null.
 180:    * @return a new instance of a {@link GnuRSAPublicKey} decoded from the
 181:    *         <i>SubjectPublicKeyInfo</i> material in an X.509 certificate.
 182:    * @throw InvalidParameterException if an exception occurs during the
 183:    *        unmarshalling process.
 184:    */
 185:   public PublicKey decodePublicKey(byte[] input)
 186:   {
 187:     if (Configuration.DEBUG)
 188:       log.entering(this.getClass().getName(), "decodePublicKey()", input);
 189:     if (input == null)
 190:       throw new InvalidParameterException("Input bytes MUST NOT be null");
 191: 
 192:     BigInteger n, e;
 193:     DERReader der = new DERReader(input);
 194:     try
 195:       {
 196:         DERValue derSPKI = der.read();
 197:         DerUtil.checkIsConstructed(derSPKI, "Wrong SubjectPublicKeyInfo field");
 198: 
 199:         DERValue derAlgorithmID = der.read();
 200:         DerUtil.checkIsConstructed(derAlgorithmID, "Wrong AlgorithmIdentifier field");
 201: 
 202:         DERValue derOID = der.read();
 203:         if (! (derOID.getValue() instanceof OID))
 204:           throw new InvalidParameterException("Wrong Algorithm field");
 205: 
 206:         OID algOID = (OID) derOID.getValue();
 207:         if (! algOID.equals(RSA_ALG_OID))
 208:           throw new InvalidParameterException("Unexpected OID: " + algOID);
 209: 
 210:         // rfc-2459 states that this field is OPTIONAL but NULL if/when present
 211:         DERValue val = der.read();
 212:         if (val.getTag() == DER.NULL)
 213:           val = der.read();
 214: 
 215:         if (! (val.getValue() instanceof BitString))
 216:           throw new InvalidParameterException("Wrong SubjectPublicKey field");
 217: 
 218:         byte[] spkBytes = ((BitString) val.getValue()).toByteArray();
 219: 
 220:         der = new DERReader(spkBytes);
 221:         val = der.read();
 222:         DerUtil.checkIsConstructed(derAlgorithmID, "Wrong subjectPublicKey field");
 223: 
 224:         val = der.read();
 225:         DerUtil.checkIsBigInteger(val, "Wrong modulus field");
 226:         n = (BigInteger) val.getValue();
 227:         val = der.read();
 228:         DerUtil.checkIsBigInteger(val, "Wrong publicExponent field");
 229:         e = (BigInteger) val.getValue();
 230:       }
 231:     catch (IOException x)
 232:       {
 233:         InvalidParameterException y = new InvalidParameterException(x.getMessage());
 234:         y.initCause(x);
 235:         throw y;
 236:       }
 237:     PublicKey result = new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
 238:     if (Configuration.DEBUG)
 239:       log.exiting(this.getClass().getName(), "decodePublicKey()", result);
 240:     return result;
 241:   }
 242: 
 243:   /**
 244:    * @throws InvalidParameterException ALWAYS.
 245:    */
 246:   public PrivateKey decodePrivateKey(byte[] input)
 247:   {
 248:     throw new InvalidParameterException("Wrong format for private keys");
 249:   }
 250: }