0N/A/*
3261N/A * Copyright (c) 1996, 2010, 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.x509;
0N/A
0N/Aimport java.io.*;
0N/Aimport java.util.Arrays;
0N/Aimport java.util.Properties;
0N/Aimport java.security.Key;
0N/Aimport java.security.PublicKey;
0N/Aimport java.security.KeyFactory;
0N/Aimport java.security.KeyRep;
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.X509EncodedKeySpec;
0N/A
0N/Aimport sun.misc.HexDumpEncoder;
0N/Aimport sun.security.util.*;
0N/A
0N/A/**
0N/A * Holds an X.509 key, for example a public key found in an X.509
0N/A * certificate. Includes a description of the algorithm to be used
0N/A * with the key; these keys normally are used as
0N/A * "SubjectPublicKeyInfo".
0N/A *
0N/A * <P>While this class can represent any kind of X.509 key, it may be
0N/A * desirable to provide subclasses which understand how to parse keying
0N/A * data. For example, RSA public keys have two members, one for the
0N/A * public modulus and one for the prime exponent. If such a class is
0N/A * provided, it is used when parsing X.509 keys. If one is not provided,
0N/A * the key still parses correctly.
0N/A *
0N/A * @author David Brownell
0N/A */
0N/Apublic class X509Key implements PublicKey {
0N/A
0N/A /** use serialVersionUID from JDK 1.1. for interoperability */
0N/A private static final long serialVersionUID = -5359250853002055002L;
0N/A
0N/A /* The algorithm information (name, parameters, etc). */
0N/A protected AlgorithmId algid;
0N/A
0N/A /**
0N/A * The key bytes, without the algorithm information.
0N/A * @deprecated Use the BitArray form which does not require keys to
0N/A * be byte aligned.
0N/A * @see sun.security.x509.X509Key#setKey(BitArray)
0N/A * @see sun.security.x509.X509Key#getKey()
0N/A */
0N/A @Deprecated
0N/A protected byte[] key = null;
0N/A
0N/A /*
0N/A * The number of bits unused in the last byte of the key.
0N/A * Added to keep the byte[] key form consistent with the BitArray
0N/A * form. Can de deleted when byte[] key is deleted.
0N/A */
0N/A private int unusedBits = 0;
0N/A
0N/A /* BitArray form of key */
0N/A private BitArray bitStringKey = null;
0N/A
0N/A /* The encoding for the key. */
0N/A protected byte[] encodedKey;
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 X509Key() { }
0N/A
0N/A /*
0N/A * Build and initialize as a "default" key. All X.509 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 X509Key(AlgorithmId algid, BitArray key)
0N/A throws InvalidKeyException {
0N/A this.algid = algid;
0N/A setKey(key);
0N/A encode();
0N/A }
0N/A
0N/A /**
0N/A * Sets the key in the BitArray form.
0N/A */
0N/A protected void setKey(BitArray key) {
0N/A this.bitStringKey = (BitArray)key.clone();
0N/A
0N/A /*
0N/A * Do this to keep the byte array form consistent with
0N/A * this. Can delete when byte[] key is deleted.
0N/A */
0N/A this.key = key.toByteArray();
0N/A int remaining = key.length() % 8;
0N/A this.unusedBits =
0N/A ((remaining == 0) ? 0 : 8 - remaining);
0N/A }
0N/A
0N/A /**
0N/A * Gets the key. The key may or may not be byte aligned.
0N/A * @return a BitArray containing the key.
0N/A */
0N/A protected BitArray getKey() {
0N/A /*
0N/A * Do this for consistency in case a subclass
0N/A * modifies byte[] key directly. Remove when
0N/A * byte[] key is deleted.
0N/A * Note: the consistency checks fail when the subclass
0N/A * modifies a non byte-aligned key (into a byte-aligned key)
0N/A * using the deprecated byte[] key field.
0N/A */
0N/A this.bitStringKey = new BitArray(
0N/A this.key.length * 8 - this.unusedBits,
0N/A this.key);
0N/A
0N/A return (BitArray)bitStringKey.clone();
0N/A }
0N/A
0N/A /**
0N/A * Construct X.509 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 * X509Key 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 PublicKey parse(DerValue in) throws IOException
0N/A {
0N/A AlgorithmId algorithm;
0N/A PublicKey subjectKey;
0N/A
0N/A if (in.tag != DerValue.tag_Sequence)
0N/A throw new IOException("corrupt subject key");
0N/A
0N/A algorithm = AlgorithmId.parse(in.data.getDerValue());
0N/A try {
0N/A subjectKey = buildX509Key(algorithm,
0N/A in.data.getUnalignedBitString());
0N/A
0N/A } catch (InvalidKeyException e) {
2308N/A throw new IOException("subject key, " + e.getMessage(), e);
0N/A }
0N/A
0N/A if (in.data.available() != 0)
0N/A throw new IOException("excess subject key");
0N/A return subjectKey;
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 X.509 SubjectPublicKeyInfo
0N/A * values using the X509Key member functions, such as <code>parse</code>
0N/A * and <code>decode</code>.
0N/A *
0N/A * @exception IOException on parsing errors.
0N/A * @exception InvalidKeyException on invalid key encodings.
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 PublicKey buildX509Key(AlgorithmId algid, BitArray 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 x509EncodedKeyStream = new DerOutputStream();
0N/A encode(x509EncodedKeyStream, algid, key);
0N/A X509EncodedKeySpec x509KeySpec
0N/A = new X509EncodedKeySpec(x509EncodedKeyStream.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 public key
0N/A return keyFac.generatePublic(x509KeySpec);
0N/A } catch (NoSuchAlgorithmException e) {
0N/A // Return generic X509Key with opaque key data (see below)
0N/A } catch (InvalidKeySpecException e) {
2308N/A throw new InvalidKeyException(e.getMessage(), e);
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("PublicKey.X.509." +
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 X509Key result;
0N/A
0N/A if (keyClass != null)
0N/A inst = keyClass.newInstance();
0N/A if (inst instanceof X509Key) {
0N/A result = (X509Key) inst;
0N/A result.algid = algid;
0N/A result.setKey(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 X509Key result = new X509Key(algid, 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 * Encode SubjectPublicKeyInfo sequence on the DER output stream.
0N/A *
0N/A * @exception IOException on encoding errors.
0N/A */
0N/A public final void encode(DerOutputStream out) throws IOException
0N/A {
0N/A encode(out, this.algid, getKey());
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 byte[] getEncoded() {
0N/A try {
0N/A return getEncodedInternal().clone();
0N/A } catch (InvalidKeyException e) {
0N/A // XXX
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A public byte[] getEncodedInternal() throws InvalidKeyException {
0N/A byte[] encoded = encodedKey;
0N/A if (encoded == null) {
0N/A try {
0N/A DerOutputStream out = new DerOutputStream();
0N/A encode(out);
0N/A encoded = out.toByteArray();
0N/A } catch (IOException e) {
0N/A throw new InvalidKeyException("IOException : " +
0N/A e.getMessage());
0N/A }
0N/A encodedKey = encoded;
0N/A }
0N/A return encoded;
0N/A }
0N/A
0N/A /**
0N/A * Returns the format for this key: "X.509"
0N/A */
0N/A public String getFormat() {
0N/A return "X.509";
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 on encoding errors.
0N/A */
0N/A public byte[] encode() throws InvalidKeyException {
0N/A return getEncodedInternal().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 X509Key object from an input stream. The data on that
0N/A * input stream must be encoded using DER, obeying the X.509
0N/A * <code>SubjectPublicKeyInfo</code> format. That is, the data is a
0N/A * sequence consisting of an algorithm ID and a bit string which holds
0N/A * the key. (That bit string is often used to encapsulate another DER
0N/A * 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 * <P>The exception to this rule is that since private keys need not
0N/A * be encoded using the X.509 <code>SubjectPublicKeyInfo</code> format,
0N/A * private keys may override this method, <code>encode</code>, and
0N/A * of course <code>getFormat</code>.
0N/A *
0N/A * @param in an input stream with a DER-encoded X.509
0N/A * SubjectPublicKeyInfo value
0N/A * @exception InvalidKeyException on parsing errors.
0N/A */
0N/A public void decode(InputStream in)
0N/A 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 algid = AlgorithmId.parse(val.data.getDerValue());
0N/A setKey(val.data.getUnalignedBitString());
0N/A parseKeyBits();
0N/A if (val.data.available() != 0)
0N/A throw new InvalidKeyException ("excess key data");
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 /**
0N/A * Serialization write ... X.509 keys serialize as
0N/A * themselves, and they're parsed when they get read back.
0N/A */
0N/A private void writeObject(ObjectOutputStream stream) throws IOException {
0N/A stream.write(getEncoded());
0N/A }
0N/A
0N/A /**
0N/A * Serialization read ... X.509 keys serialize as
0N/A * themselves, and they're parsed when they get read back.
0N/A */
0N/A private void readObject(ObjectInputStream stream) throws IOException {
0N/A try {
0N/A decode(stream);
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 public boolean equals(Object obj) {
0N/A if (this == obj) {
0N/A return true;
0N/A }
0N/A if (obj instanceof Key == false) {
0N/A return false;
0N/A }
0N/A try {
0N/A byte[] thisEncoded = this.getEncodedInternal();
0N/A byte[] otherEncoded;
0N/A if (obj instanceof X509Key) {
0N/A otherEncoded = ((X509Key)obj).getEncodedInternal();
0N/A } else {
0N/A otherEncoded = ((Key)obj).getEncoded();
0N/A }
0N/A return Arrays.equals(thisEncoded, otherEncoded);
0N/A } catch (InvalidKeyException e) {
0N/A return false;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Calculates a hash code value for the object. Objects
0N/A * which are equal will also have the same hashcode.
0N/A */
0N/A public int hashCode() {
0N/A try {
0N/A byte[] b1 = getEncodedInternal();
0N/A int r = b1.length;
0N/A for (int i = 0; i < b1.length; i++) {
0N/A r += (b1[i] & 0xff) * 37;
0N/A }
0N/A return r;
0N/A } catch (InvalidKeyException e) {
0N/A // should not happen
0N/A return 0;
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Produce SubjectPublicKey encoding from algorithm id and key material.
0N/A */
0N/A static void encode(DerOutputStream out, AlgorithmId algid, BitArray key)
0N/A throws IOException {
0N/A DerOutputStream tmp = new DerOutputStream();
0N/A algid.encode(tmp);
0N/A tmp.putUnalignedBitString(key);
0N/A out.write(DerValue.tag_Sequence, tmp);
0N/A }
0N/A}