8244565: Accept PKCS #8 with version number 1

Reviewed-by: valeriep
This commit is contained in:
Weijun Wang 2020-06-05 07:53:50 +08:00
parent 0db1be28c7
commit 507816d550
8 changed files with 222 additions and 618 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,29 +26,36 @@
package sun.security.pkcs;
import java.io.*;
import java.util.Properties;
import java.math.*;
import java.security.Key;
import java.security.KeyRep;
import java.security.PrivateKey;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.Security;
import java.security.Provider;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import sun.security.util.HexDumpEncoder;
import sun.security.x509.*;
import sun.security.util.*;
/**
* Holds a PKCS#8 key, for example a private key
*
* @author Dave Brownell
* @author Benjamin Renaud
* According to https://tools.ietf.org/html/rfc5958:
*
* OneAsymmetricKey ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] Attributes OPTIONAL,
* ...,
* [[2: publicKey [1] PublicKey OPTIONAL ]],
* ...
* }
*
* We support this format but do not parse attributes and publicKey now.
*/
public class PKCS8Key implements PrivateKey {
@ -62,186 +69,100 @@ public class PKCS8Key implements PrivateKey {
/* The key bytes, without the algorithm information */
protected byte[] key;
/* The encoded for the key. */
/* The encoded for the key. Created on demand by encode(). */
protected byte[] encodedKey;
/* The version for this key */
public static final BigInteger version = BigInteger.ZERO;
private static final int V1 = 0;
private static final int V2 = 1;
/**
* Default constructor. The key constructed must have its key
* and algorithm initialized before it may be used, for example
* by using <code>decode</code>.
* Default constructor. Constructors in sub-classes that create a new key
* from its components require this. These constructors must initialize
* {@link #algid} and {@link #key}.
*/
public PKCS8Key() { }
protected PKCS8Key() { }
/*
* Build and initialize as a "default" key. All PKCS#8 key
* data is stored and transmitted losslessly, but no knowledge
* about this particular algorithm is available.
/**
* Another constructor. Constructors in sub-classes that create a new key
* from an encoded byte array require this. We do not assign this
* encoding to {@link #encodedKey} directly.
*
* This method is also used by {@link #parseKey} to create a raw key.
*/
private PKCS8Key (AlgorithmId algid, byte[] key)
throws InvalidKeyException {
this.algid = algid;
this.key = key;
encode();
protected PKCS8Key(byte[] input) throws InvalidKeyException {
decode(new ByteArrayInputStream(input));
}
/*
* Binary backwards compatibility. New uses should call parseKey().
*/
public static PKCS8Key parse (DerValue in) throws IOException {
PrivateKey key;
private void decode(InputStream is) throws InvalidKeyException {
try {
DerValue val = new DerValue(is);
if (val.tag != DerValue.tag_Sequence) {
throw new InvalidKeyException("invalid key format");
}
key = parseKey(in);
if (key instanceof PKCS8Key)
return (PKCS8Key)key;
int version = val.data.getInteger();
if (version != V1 && version != V2) {
throw new InvalidKeyException("unknown version: " + version);
}
algid = AlgorithmId.parse (val.data.getDerValue ());
key = val.data.getOctetString ();
throw new IOException("Provider did not return PKCS8Key");
DerValue next;
if (val.data.available() == 0) {
return;
}
next = val.data.getDerValue();
if (next.isContextSpecific((byte)0)) {
if (val.data.available() == 0) {
return;
}
next = val.data.getDerValue();
}
if (next.isContextSpecific((byte)1)) {
if (version == V1) {
throw new InvalidKeyException("publicKey seen in v1");
}
if (val.data.available() == 0) {
return;
}
}
throw new InvalidKeyException("Extra bytes");
} catch (IOException e) {
throw new InvalidKeyException("IOException : " + e.getMessage());
}
}
/**
* Construct PKCS#8 subject public key from a DER value. If
* the runtime environment is configured with a specific class for
* this kind of key, a subclass is returned. Otherwise, a generic
* Construct PKCS#8 subject public key from a DER value. If a
* security provider supports the key algorithm with a specific class,
* a PrivateKey from the provider is returned. Otherwise, a raw
* PKCS8Key object is returned.
*
* <P>This mechanism gurantees that keys (and algorithms) may be
* <P>This mechanism guarantees that keys (and algorithms) may be
* freely manipulated and transferred, without risk of losing
* information. Also, when a key (or algorithm) needs some special
* handling, that specific need can be accomodated.
* handling, that specific need can be accommodated.
*
* @param in the DER-encoded SubjectPublicKeyInfo value
* @exception IOException on data format errors
*/
public static PrivateKey parseKey (DerValue in) throws IOException
{
AlgorithmId algorithm;
PrivateKey privKey;
if (in.tag != DerValue.tag_Sequence)
throw new IOException ("corrupt private key");
BigInteger parsedVersion = in.data.getBigInteger();
if (!version.equals(parsedVersion)) {
throw new IOException("version mismatch: (supported: " +
Debug.toHexString(version) +
", parsed: " +
Debug.toHexString(parsedVersion));
}
algorithm = AlgorithmId.parse (in.data.getDerValue ());
public static PrivateKey parseKey(DerValue in) throws IOException {
try {
privKey = buildPKCS8Key (algorithm, in.data.getOctetString ());
} catch (InvalidKeyException e) {
throw new IOException("corrupt private key");
}
if (in.data.available () != 0)
throw new IOException ("excess private key");
return privKey;
}
/**
* Parse the key bits. This may be redefined by subclasses to take
* advantage of structure within the key. For example, RSA public
* keys encapsulate two unsigned integers (modulus and exponent) as
* DER values within the <code>key</code> bits; Diffie-Hellman and
* DSS/DSA keys encapsulate a single unsigned integer.
*
* <P>This function is called when creating PKCS#8 SubjectPublicKeyInfo
* values using the PKCS8Key member functions, such as <code>parse</code>
* and <code>decode</code>.
*
* @exception IOException if a parsing error occurs.
* @exception InvalidKeyException if the key encoding is invalid.
*/
protected void parseKeyBits () throws IOException, InvalidKeyException {
encode();
}
/*
* Factory interface, building the kind of key associated with this
* specific algorithm ID or else returning this generic base class.
* See the description above.
*/
static PrivateKey buildPKCS8Key (AlgorithmId algid, byte[] key)
throws IOException, InvalidKeyException
{
/*
* Use the algid and key parameters to produce the ASN.1 encoding
* of the key, which will then be used as the input to the
* key factory.
*/
DerOutputStream pkcs8EncodedKeyStream = new DerOutputStream();
encode(pkcs8EncodedKeyStream, algid, key);
PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(pkcs8EncodedKeyStream.toByteArray());
try {
// Instantiate the key factory of the appropriate algorithm
KeyFactory keyFac = KeyFactory.getInstance(algid.getName());
// Generate the private key
return keyFac.generatePrivate(pkcs8KeySpec);
} catch (NoSuchAlgorithmException e) {
// Return generic PKCS8Key with opaque key data (see below)
} catch (InvalidKeySpecException e) {
// Return generic PKCS8Key with opaque key data (see below)
}
/*
* Try again using JDK1.1-style for backwards compatibility.
*/
String classname = "";
try {
Properties props;
String keytype;
Provider sunProvider;
sunProvider = Security.getProvider("SUN");
if (sunProvider == null)
throw new InstantiationException();
classname = sunProvider.getProperty("PrivateKey.PKCS#8." +
algid.getName());
if (classname == null) {
throw new InstantiationException();
}
Class<?> keyClass = null;
PKCS8Key rawKey = new PKCS8Key(in.toByteArray());
PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(rawKey.getEncoded());
try {
keyClass = Class.forName(classname);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
keyClass = cl.loadClass(classname);
}
return KeyFactory.getInstance(rawKey.algid.getName())
.generatePrivate(pkcs8KeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// Ignore and return raw key
return rawKey;
}
@SuppressWarnings("deprecation")
Object inst = (keyClass != null) ? keyClass.newInstance() : null;
PKCS8Key result;
if (inst instanceof PKCS8Key) {
result = (PKCS8Key) inst;
result.algid = algid;
result.key = key;
result.parseKeyBits();
return result;
}
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
// this should not happen.
throw new IOException (classname + " [internal error]");
} catch (InvalidKeyException e) {
throw new IOException("corrupt private key", e);
}
PKCS8Key result = new PKCS8Key();
result.algid = algid;
result.key = key;
return result;
}
/**
@ -254,26 +175,22 @@ public class PKCS8Key implements PrivateKey {
/**
* Returns the algorithm ID to be used with this key.
*/
public AlgorithmId getAlgorithmId () { return algid; }
/**
* PKCS#8 sequence on the DER output stream.
*/
public final void encode(DerOutputStream out) throws IOException
{
encode(out, this.algid, this.key);
public AlgorithmId getAlgorithmId () {
return algid;
}
/**
* Returns the DER-encoded form of the key as a byte array.
* Returns the DER-encoded form of the key as a byte array,
* or {@code null} if an encoding error occurs.
*/
public synchronized byte[] getEncoded() {
byte[] result = null;
try {
result = encode();
encode();
return encodedKey.clone();
} catch (InvalidKeyException e) {
// ignored and return null
}
return result;
return null;
}
/**
@ -284,76 +201,26 @@ public class PKCS8Key implements PrivateKey {
}
/**
* Returns the DER-encoded form of the key as a byte array.
* DER-encodes this key as a byte array that can be retrieved
* by the {@link #getEncoded()} method.
*
* @exception InvalidKeyException if an encoding error occurs.
*/
public byte[] encode() throws InvalidKeyException {
private void encode() throws InvalidKeyException {
if (encodedKey == null) {
try {
DerOutputStream out;
out = new DerOutputStream ();
encode (out);
DerOutputStream out = new DerOutputStream ();
DerOutputStream tmp = new DerOutputStream();
tmp.putInteger(V1);
algid.encode(tmp);
tmp.putOctetString(key);
out.write(DerValue.tag_Sequence, tmp);
encodedKey = out.toByteArray();
} catch (IOException e) {
throw new InvalidKeyException ("IOException : " +
e.getMessage());
}
}
return encodedKey.clone();
}
/**
* Initialize an PKCS8Key object from an input stream. The data
* on that input stream must be encoded using DER, obeying the
* PKCS#8 format: a sequence consisting of a version, an algorithm
* ID and a bit string which holds the key. (That bit string is
* often used to encapsulate another DER encoded sequence.)
*
* <P>Subclasses should not normally redefine this method; they should
* instead provide a <code>parseKeyBits</code> method to parse any
* fields inside the <code>key</code> member.
*
* @param in an input stream with a DER-encoded PKCS#8
* SubjectPublicKeyInfo value
*
* @exception InvalidKeyException if a parsing error occurs.
*/
public void decode(InputStream in) throws InvalidKeyException
{
DerValue val;
try {
val = new DerValue (in);
if (val.tag != DerValue.tag_Sequence)
throw new InvalidKeyException ("invalid key format");
BigInteger version = val.data.getBigInteger();
if (!version.equals(PKCS8Key.version)) {
throw new IOException("version mismatch: (supported: " +
Debug.toHexString(PKCS8Key.version) +
", parsed: " +
Debug.toHexString(version));
}
algid = AlgorithmId.parse (val.data.getDerValue ());
key = val.data.getOctetString ();
parseKeyBits ();
if (val.data.available () != 0) {
// OPTIONAL attributes not supported yet
}
} catch (IOException e) {
throw new InvalidKeyException("IOException : " +
e.getMessage());
}
}
public void decode(byte[] encodedKey) throws InvalidKeyException {
decode(new ByteArrayInputStream(encodedKey));
}
@java.io.Serial
@ -365,35 +232,18 @@ public class PKCS8Key implements PrivateKey {
}
/**
* Serialization read ... PKCS#8 keys serialize as
* themselves, and they're parsed when they get read back.
* We used to serialize a PKCS8Key as itself (instead of a KeyRep).
*/
@java.io.Serial
private void readObject (ObjectInputStream stream)
throws IOException {
private void readObject(ObjectInputStream stream) throws IOException {
try {
decode(stream);
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new IOException("deserialized key is invalid: " +
e.getMessage());
}
}
/*
* Produce PKCS#8 encoding from algorithm id and key material.
*/
static void encode(DerOutputStream out, AlgorithmId algid, byte[] key)
throws IOException {
DerOutputStream tmp = new DerOutputStream();
tmp.putInteger(version);
algid.encode(tmp);
tmp.putOctetString(key);
out.write(DerValue.tag_Sequence, tmp);
}
/**
* Compares two private keys. This returns false if the object with which
* to compare is not of type <code>Key</code>.
@ -401,29 +251,18 @@ public class PKCS8Key implements PrivateKey {
* encoding of the given key object.
*
* @param object the object with which to compare
* @return <code>true</code> if this key has the same encoding as the
* object argument; <code>false</code> otherwise.
* @return {@code true} if this key has the same encoding as the
* object argument; {@code false} otherwise.
*/
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Key) {
// this encoding
byte[] b1;
if (encodedKey != null) {
b1 = encodedKey;
} else {
b1 = getEncoded();
}
// that encoding
byte[] b2 = ((Key)object).getEncoded();
// time-constant comparison
return MessageDigest.isEqual(b1, b2);
return MessageDigest.isEqual(
getEncoded(),
((Key)object).getEncoded());
}
return false;
}
@ -433,12 +272,6 @@ public class PKCS8Key implements PrivateKey {
* which are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
byte[] b1 = getEncoded();
for (int i = 1; i < b1.length; i++) {
retval += b1[i] * i;
}
return(retval);
return Arrays.hashCode(getEncoded());
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,11 +25,9 @@
package sun.security.provider;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.ProviderException;
import java.security.AlgorithmParameters;
import java.security.spec.DSAParameterSpec;
import java.security.spec.InvalidParameterSpecException;
@ -37,10 +35,8 @@ import java.security.interfaces.DSAParams;
import sun.security.x509.AlgIdDSA;
import sun.security.pkcs.PKCS8Key;
import sun.security.util.Debug;
import sun.security.util.DerValue;
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
/**
* A PKCS#8 private key for the Digital Signature Algorithm.
@ -54,7 +50,7 @@ import sun.security.util.DerOutputStream;
*/
public final class DSAPrivateKey extends PKCS8Key
implements java.security.interfaces.DSAPrivateKey, Serializable {
implements java.security.interfaces.DSAPrivateKey, Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
@java.io.Serial
@ -63,30 +59,19 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
/* the private key */
private BigInteger x;
/*
* Keep this constructor for backwards compatibility with JDK1.1.
*/
public DSAPrivateKey() {
}
/**
* Make a DSA private key out of a private key and three parameters.
*/
public DSAPrivateKey(BigInteger x, BigInteger p,
BigInteger q, BigInteger g)
throws InvalidKeyException {
BigInteger q, BigInteger g) {
this.x = x;
algid = new AlgIdDSA(p, q, g);
try {
key = new DerValue(DerValue.tag_Integer,
x.toByteArray()).toByteArray();
encode();
} catch (IOException e) {
InvalidKeyException ike = new InvalidKeyException(
"could not DER encode x: " + e.getMessage());
ike.initCause(e);
throw ike;
throw new AssertionError("Should not happen", e);
}
}
@ -94,8 +79,13 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
* Make a DSA private key from its DER encoding (PKCS #8).
*/
public DSAPrivateKey(byte[] encoded) throws InvalidKeyException {
clearOldKey();
decode(encoded);
super(encoded);
try {
DerInputStream in = new DerInputStream(key);
x = in.getBigInteger();
} catch (IOException e) {
throw new InvalidKeyException(e.getMessage(), e);
}
}
/**
@ -113,7 +103,7 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
return paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
@ -122,35 +112,8 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
/**
* Get the raw private key, x, without the parameters.
*
* @see getParameters
*/
public BigInteger getX() {
return x;
}
private void clearOldKey() {
int i;
if (this.encodedKey != null) {
for (i = 0; i < this.encodedKey.length; i++) {
this.encodedKey[i] = (byte)0x00;
}
}
if (this.key != null) {
for (i = 0; i < this.key.length; i++) {
this.key[i] = (byte)0x00;
}
}
}
protected void parseKeyBits() throws InvalidKeyException {
try {
DerInputStream in = new DerInputStream(key);
x = in.getBigInteger();
} catch (IOException e) {
InvalidKeyException ike = new InvalidKeyException(e.getMessage());
ike.initCause(e);
throw ike;
}
}
}

View file

@ -79,6 +79,9 @@ public final class RSAPrivateCrtKeyImpl
*/
public static RSAPrivateKey newKey(byte[] encoded)
throws InvalidKeyException {
if (encoded == null || encoded.length == 0) {
throw new InvalidKeyException("Missing key encoding");
}
RSAPrivateCrtKeyImpl key = new RSAPrivateCrtKeyImpl(encoded);
// check all CRT-specific components are available, if any one
// missing, return a non-CRT key instead
@ -124,11 +127,8 @@ public final class RSAPrivateCrtKeyImpl
* Construct a key from its encoding. Called from newKey above.
*/
RSAPrivateCrtKeyImpl(byte[] encoded) throws InvalidKeyException {
if (encoded == null || encoded.length == 0) {
throw new InvalidKeyException("Missing key encoding");
}
decode(encoded);
super(encoded);
parseKeyBits();
RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
try {
// check the validity of oid and params
@ -258,10 +258,7 @@ public final class RSAPrivateCrtKeyImpl
+ "\n modulus: " + n + "\n private exponent: " + d;
}
/**
* Parse the key. Called by PKCS8Key.
*/
protected void parseKeyBits() throws InvalidKeyException {
private void parseKeyBits() throws InvalidKeyException {
try {
DerInputStream in = new DerInputStream(key);
DerValue derValue = in.getDerValue();