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

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