0N/A/*
2362N/A * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage sun.security.pkcs;
0N/A
0N/Aimport java.io.*;
0N/Aimport java.util.Properties;
0N/Aimport java.math.*;
0N/Aimport java.security.Key;
0N/Aimport java.security.KeyRep;
0N/Aimport java.security.PrivateKey;
0N/Aimport java.security.KeyFactory;
0N/Aimport java.security.Security;
0N/Aimport java.security.Provider;
0N/Aimport java.security.InvalidKeyException;
0N/Aimport java.security.NoSuchAlgorithmException;
0N/Aimport java.security.spec.InvalidKeySpecException;
0N/Aimport java.security.spec.PKCS8EncodedKeySpec;
0N/A
0N/Aimport sun.misc.HexDumpEncoder;
0N/Aimport sun.security.x509.*;
0N/Aimport sun.security.util.*;
0N/A
0N/A/**
0N/A * Holds a PKCS#8 key, for example a private key
0N/A *
0N/A * @author Dave Brownell
0N/A * @author Benjamin Renaud
0N/A */
0N/Apublic class PKCS8Key implements PrivateKey {
0N/A
0N/A /** use serialVersionUID from JDK 1.1. for interoperability */
0N/A private static final long serialVersionUID = -3836890099307167124L;
0N/A
0N/A /* The algorithm information (name, parameters, etc). */
0N/A protected AlgorithmId algid;
0N/A
0N/A /* The key bytes, without the algorithm information */
0N/A protected byte[] key;
0N/A
0N/A /* The encoded for the key. */
0N/A protected byte[] encodedKey;
0N/A
0N/A /* The version for this key */
0N/A public static final BigInteger version = BigInteger.ZERO;
0N/A
0N/A /**
0N/A * Default constructor. The key constructed must have its key
0N/A * and algorithm initialized before it may be used, for example
0N/A * by using <code>decode</code>.
0N/A */
0N/A public PKCS8Key() { }
0N/A
0N/A /*
0N/A * Build and initialize as a "default" key. All PKCS#8 key
0N/A * data is stored and transmitted losslessly, but no knowledge
0N/A * about this particular algorithm is available.
0N/A */
0N/A private PKCS8Key (AlgorithmId algid, byte key [])
0N/A throws InvalidKeyException {
0N/A this.algid = algid;
0N/A this.key = key;
0N/A encode();
0N/A }
0N/A
0N/A /*
0N/A * Binary backwards compatibility. New uses should call parseKey().
0N/A */
0N/A public static PKCS8Key parse (DerValue in) throws IOException {
0N/A PrivateKey key;
0N/A
0N/A key = parseKey(in);
0N/A if (key instanceof PKCS8Key)
0N/A return (PKCS8Key)key;
0N/A
0N/A throw new IOException("Provider did not return PKCS8Key");
0N/A }
0N/A
0N/A /**
0N/A * Construct PKCS#8 subject public key from a DER value. If
0N/A * the runtime environment is configured with a specific class for
0N/A * this kind of key, a subclass is returned. Otherwise, a generic
0N/A * PKCS8Key object is returned.
0N/A *
0N/A * <P>This mechanism gurantees that keys (and algorithms) may be
0N/A * freely manipulated and transferred, without risk of losing
0N/A * information. Also, when a key (or algorithm) needs some special
0N/A * handling, that specific need can be accomodated.
0N/A *
0N/A * @param in the DER-encoded SubjectPublicKeyInfo value
0N/A * @exception IOException on data format errors
0N/A */
0N/A public static PrivateKey parseKey (DerValue in) throws IOException
0N/A {
0N/A AlgorithmId algorithm;
0N/A PrivateKey privKey;
0N/A
0N/A if (in.tag != DerValue.tag_Sequence)
0N/A throw new IOException ("corrupt private key");
0N/A
0N/A BigInteger parsedVersion = in.data.getBigInteger();
0N/A if (!version.equals(parsedVersion)) {
0N/A throw new IOException("version mismatch: (supported: " +
0N/A Debug.toHexString(version) +
0N/A ", parsed: " +
0N/A Debug.toHexString(parsedVersion));
0N/A }
0N/A
0N/A algorithm = AlgorithmId.parse (in.data.getDerValue ());
0N/A
0N/A try {
0N/A privKey = buildPKCS8Key (algorithm, in.data.getOctetString ());
0N/A
0N/A } catch (InvalidKeyException e) {
0N/A throw new IOException("corrupt private key");
0N/A }
0N/A
0N/A if (in.data.available () != 0)
0N/A throw new IOException ("excess private key");
0N/A return privKey;
0N/A }
0N/A
0N/A /**
0N/A * Parse the key bits. This may be redefined by subclasses to take
0N/A * advantage of structure within the key. For example, RSA public
0N/A * keys encapsulate two unsigned integers (modulus and exponent) as
0N/A * DER values within the <code>key</code> bits; Diffie-Hellman and
0N/A * DSS/DSA keys encapsulate a single unsigned integer.
0N/A *
0N/A * <P>This function is called when creating PKCS#8 SubjectPublicKeyInfo
0N/A * values using the PKCS8Key member functions, such as <code>parse</code>
0N/A * and <code>decode</code>.
0N/A *
0N/A * @exception IOException if a parsing error occurs.
0N/A * @exception InvalidKeyException if the key encoding is invalid.
0N/A */
0N/A protected void parseKeyBits () throws IOException, InvalidKeyException {
0N/A encode();
0N/A }
0N/A
0N/A /*
0N/A * Factory interface, building the kind of key associated with this
0N/A * specific algorithm ID or else returning this generic base class.
0N/A * See the description above.
0N/A */
0N/A static PrivateKey buildPKCS8Key (AlgorithmId algid, byte[] key)
0N/A throws IOException, InvalidKeyException
0N/A {
0N/A /*
0N/A * Use the algid and key parameters to produce the ASN.1 encoding
0N/A * of the key, which will then be used as the input to the
0N/A * key factory.
0N/A */
0N/A DerOutputStream pkcs8EncodedKeyStream = new DerOutputStream();
0N/A encode(pkcs8EncodedKeyStream, algid, key);
0N/A PKCS8EncodedKeySpec pkcs8KeySpec
0N/A = new PKCS8EncodedKeySpec(pkcs8EncodedKeyStream.toByteArray());
0N/A
0N/A try {
0N/A // Instantiate the key factory of the appropriate algorithm
0N/A KeyFactory keyFac = KeyFactory.getInstance(algid.getName());
0N/A
0N/A // Generate the private key
0N/A return keyFac.generatePrivate(pkcs8KeySpec);
0N/A } catch (NoSuchAlgorithmException e) {
0N/A // Return generic PKCS8Key with opaque key data (see below)
0N/A } catch (InvalidKeySpecException e) {
0N/A // Return generic PKCS8Key with opaque key data (see below)
0N/A }
0N/A
0N/A /*
0N/A * Try again using JDK1.1-style for backwards compatibility.
0N/A */
0N/A String classname = "";
0N/A try {
0N/A Properties props;
0N/A String keytype;
0N/A Provider sunProvider;
0N/A
0N/A sunProvider = Security.getProvider("SUN");
0N/A if (sunProvider == null)
0N/A throw new InstantiationException();
0N/A classname = sunProvider.getProperty("PrivateKey.PKCS#8." +
0N/A algid.getName());
0N/A if (classname == null) {
0N/A throw new InstantiationException();
0N/A }
0N/A
0N/A Class keyClass = null;
0N/A try {
0N/A keyClass = Class.forName(classname);
0N/A } catch (ClassNotFoundException e) {
0N/A ClassLoader cl = ClassLoader.getSystemClassLoader();
0N/A if (cl != null) {
0N/A keyClass = cl.loadClass(classname);
0N/A }
0N/A }
0N/A
0N/A Object inst = null;
0N/A PKCS8Key result;
0N/A
0N/A if (keyClass != null)
0N/A inst = keyClass.newInstance();
0N/A if (inst instanceof PKCS8Key) {
0N/A result = (PKCS8Key) inst;
0N/A result.algid = algid;
0N/A result.key = key;
0N/A result.parseKeyBits();
0N/A return result;
0N/A }
0N/A } catch (ClassNotFoundException e) {
0N/A } catch (InstantiationException e) {
0N/A } catch (IllegalAccessException e) {
0N/A // this should not happen.
0N/A throw new IOException (classname + " [internal error]");
0N/A }
0N/A
0N/A PKCS8Key result = new PKCS8Key();
0N/A result.algid = algid;
0N/A result.key = key;
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns the algorithm to be used with this key.
0N/A */
0N/A public String getAlgorithm() {
0N/A return algid.getName();
0N/A }
0N/A
0N/A /**
0N/A * Returns the algorithm ID to be used with this key.
0N/A */
0N/A public AlgorithmId getAlgorithmId () { return algid; }
0N/A
0N/A /**
0N/A * PKCS#8 sequence on the DER output stream.
0N/A */
0N/A public final void encode(DerOutputStream out) throws IOException
0N/A {
0N/A encode(out, this.algid, this.key);
0N/A }
0N/A
0N/A /**
0N/A * Returns the DER-encoded form of the key as a byte array.
0N/A */
0N/A public synchronized byte[] getEncoded() {
0N/A byte[] result = null;
0N/A try {
0N/A result = encode();
0N/A } catch (InvalidKeyException e) {
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns the format for this key: "PKCS#8"
0N/A */
0N/A public String getFormat() {
0N/A return "PKCS#8";
0N/A }
0N/A
0N/A /**
0N/A * Returns the DER-encoded form of the key as a byte array.
0N/A *
0N/A * @exception InvalidKeyException if an encoding error occurs.
0N/A */
0N/A public byte[] encode() throws InvalidKeyException {
0N/A if (encodedKey == null) {
0N/A try {
0N/A DerOutputStream out;
0N/A
0N/A out = new DerOutputStream ();
0N/A encode (out);
0N/A encodedKey = out.toByteArray();
0N/A
0N/A } catch (IOException e) {
0N/A throw new InvalidKeyException ("IOException : " +
0N/A e.getMessage());
0N/A }
0N/A }
0N/A return encodedKey.clone();
0N/A }
0N/A
0N/A /*
0N/A * Returns a printable representation of the key
0N/A */
0N/A public String toString ()
0N/A {
0N/A HexDumpEncoder encoder = new HexDumpEncoder ();
0N/A
0N/A return "algorithm = " + algid.toString ()
0N/A + ", unparsed keybits = \n" + encoder.encodeBuffer (key);
0N/A }
0N/A
0N/A /**
0N/A * Initialize an PKCS8Key object from an input stream. The data
0N/A * on that input stream must be encoded using DER, obeying the
0N/A * PKCS#8 format: a sequence consisting of a version, an algorithm
0N/A * ID and a bit string which holds the key. (That bit string is
0N/A * often used to encapsulate another DER encoded sequence.)
0N/A *
0N/A * <P>Subclasses should not normally redefine this method; they should
0N/A * instead provide a <code>parseKeyBits</code> method to parse any
0N/A * fields inside the <code>key</code> member.
0N/A *
0N/A * @param in an input stream with a DER-encoded PKCS#8
0N/A * SubjectPublicKeyInfo value
0N/A *
0N/A * @exception InvalidKeyException if a parsing error occurs.
0N/A */
0N/A public void decode(InputStream in) throws InvalidKeyException
0N/A {
0N/A DerValue val;
0N/A
0N/A try {
0N/A val = new DerValue (in);
0N/A if (val.tag != DerValue.tag_Sequence)
0N/A throw new InvalidKeyException ("invalid key format");
0N/A
0N/A
0N/A BigInteger version = val.data.getBigInteger();
0N/A if (!version.equals(this.version)) {
0N/A throw new IOException("version mismatch: (supported: " +
0N/A Debug.toHexString(this.version) +
0N/A ", parsed: " +
0N/A Debug.toHexString(version));
0N/A }
0N/A algid = AlgorithmId.parse (val.data.getDerValue ());
0N/A key = val.data.getOctetString ();
0N/A parseKeyBits ();
0N/A
0N/A if (val.data.available () != 0) {
0N/A // OPTIONAL attributes not supported yet
0N/A }
0N/A
0N/A } catch (IOException e) {
0N/A // e.printStackTrace ();
0N/A throw new InvalidKeyException("IOException : " +
0N/A e.getMessage());
0N/A }
0N/A }
0N/A
0N/A public void decode(byte[] encodedKey) throws InvalidKeyException {
0N/A decode(new ByteArrayInputStream(encodedKey));
0N/A }
0N/A
0N/A protected Object writeReplace() throws java.io.ObjectStreamException {
0N/A return new KeyRep(KeyRep.Type.PRIVATE,
0N/A getAlgorithm(),
0N/A getFormat(),
0N/A getEncoded());
0N/A }
0N/A
0N/A /**
0N/A * Serialization read ... PKCS#8 keys serialize as
0N/A * themselves, and they're parsed when they get read back.
0N/A */
0N/A private void readObject (ObjectInputStream stream)
0N/A throws IOException {
0N/A
0N/A try {
0N/A decode(stream);
0N/A
0N/A } catch (InvalidKeyException e) {
0N/A e.printStackTrace();
0N/A throw new IOException("deserialized key is invalid: " +
0N/A e.getMessage());
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Produce PKCS#8 encoding from algorithm id and key material.
0N/A */
0N/A static void encode(DerOutputStream out, AlgorithmId algid, byte[] key)
0N/A throws IOException {
0N/A DerOutputStream tmp = new DerOutputStream();
0N/A tmp.putInteger(version);
0N/A algid.encode(tmp);
0N/A tmp.putOctetString(key);
0N/A out.write(DerValue.tag_Sequence, tmp);
0N/A }
0N/A
0N/A /**
0N/A * Compares two private keys. This returns false if the object with which
0N/A * to compare is not of type <code>Key</code>.
0N/A * Otherwise, the encoding of this key object is compared with the
0N/A * encoding of the given key object.
0N/A *
0N/A * @param object the object with which to compare
0N/A * @return <code>true</code> if this key has the same encoding as the
0N/A * object argument; <code>false</code> otherwise.
0N/A */
0N/A public boolean equals(Object object) {
0N/A if (this == object) {
0N/A return true;
0N/A }
0N/A
0N/A if (object instanceof Key) {
0N/A
0N/A // this encoding
0N/A byte[] b1;
0N/A if (encodedKey != null) {
0N/A b1 = encodedKey;
0N/A } else {
0N/A b1 = getEncoded();
0N/A }
0N/A
0N/A // that encoding
0N/A byte[] b2 = ((Key)object).getEncoded();
0N/A
0N/A // do the comparison
0N/A int i;
0N/A if (b1.length != b2.length)
0N/A return false;
0N/A for (i = 0; i < b1.length; i++) {
0N/A if (b1[i] != b2[i]) {
0N/A return false;
0N/A }
0N/A }
0N/A return true;
0N/A }
0N/A
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Calculates a hash code value for this object. Objects
0N/A * which are equal will also have the same hashcode.
0N/A */
0N/A public int hashCode() {
0N/A int retval = 0;
0N/A byte[] b1 = getEncoded();
0N/A
0N/A for (int i = 1; i < b1.length; i++) {
0N/A retval += b1[i] * i;
0N/A }
0N/A return(retval);
0N/A }
0N/A}