6953295: Move few sun.security.{util, x509, pkcs} classes used by keytool/jarsigner to another package
Reviewed-by: mchung
--- a/jdk/make/sun/security/other/Makefile Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/make/sun/security/other/Makefile Thu Oct 13 13:50:17 2011 -0400
@@ -38,6 +38,7 @@
sun/security/acl \
sun/security/jca \
sun/security/pkcs \
+ sun/security/pkcs10 \
sun/security/pkcs12 \
sun/security/provider \
sun/security/rsa \
--- a/jdk/src/share/classes/sun/security/pkcs/EncodingException.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 1996, 2003, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/**
- * Generic PKCS Encoding exception.
- *
- * @author Benjamin Renaud
- */
-
-package sun.security.pkcs;
-
-public class EncodingException extends Exception {
-
- private static final long serialVersionUID = 4060198374240668325L;
-
- public EncodingException() {
- super();
- }
-
- public EncodingException(String s) {
- super(s);
- }
-}
--- a/jdk/src/share/classes/sun/security/pkcs/PKCS10.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,353 +0,0 @@
-/*
- * Copyright (c) 1996, 2011, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-
-package sun.security.pkcs;
-
-import java.io.PrintStream;
-import java.io.IOException;
-import java.math.BigInteger;
-
-import java.security.cert.CertificateException;
-import java.security.NoSuchAlgorithmException;
-import java.security.InvalidKeyException;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.PublicKey;
-
-import sun.misc.BASE64Encoder;
-
-import sun.security.util.*;
-import sun.security.x509.AlgorithmId;
-import sun.security.x509.X509Key;
-import sun.security.x509.X500Name;
-
-/**
- * A PKCS #10 certificate request is created and sent to a Certificate
- * Authority, which then creates an X.509 certificate and returns it to
- * the entity that requested it. A certificate request basically consists
- * of the subject's X.500 name, public key, and optionally some attributes,
- * signed using the corresponding private key.
- *
- * The ASN.1 syntax for a Certification Request is:
- * <pre>
- * CertificationRequest ::= SEQUENCE {
- * certificationRequestInfo CertificationRequestInfo,
- * signatureAlgorithm SignatureAlgorithmIdentifier,
- * signature Signature
- * }
- *
- * SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
- * Signature ::= BIT STRING
- *
- * CertificationRequestInfo ::= SEQUENCE {
- * version Version,
- * subject Name,
- * subjectPublicKeyInfo SubjectPublicKeyInfo,
- * attributes [0] IMPLICIT Attributes
- * }
- * Attributes ::= SET OF Attribute
- * </pre>
- *
- * @author David Brownell
- * @author Amit Kapoor
- * @author Hemma Prafullchandra
- */
-public class PKCS10 {
- /**
- * Constructs an unsigned PKCS #10 certificate request. Before this
- * request may be used, it must be encoded and signed. Then it
- * must be retrieved in some conventional format (e.g. string).
- *
- * @param publicKey the public key that should be placed
- * into the certificate generated by the CA.
- */
- public PKCS10(PublicKey publicKey) {
- subjectPublicKeyInfo = publicKey;
- attributeSet = new PKCS10Attributes();
- }
-
- /**
- * Constructs an unsigned PKCS #10 certificate request. Before this
- * request may be used, it must be encoded and signed. Then it
- * must be retrieved in some conventional format (e.g. string).
- *
- * @param publicKey the public key that should be placed
- * into the certificate generated by the CA.
- * @param attributes additonal set of PKCS10 attributes requested
- * for in the certificate.
- */
- public PKCS10(PublicKey publicKey, PKCS10Attributes attributes) {
- subjectPublicKeyInfo = publicKey;
- attributeSet = attributes;
- }
-
- /**
- * Parses an encoded, signed PKCS #10 certificate request, verifying
- * the request's signature as it does so. This constructor would
- * typically be used by a Certificate Authority, from which a new
- * certificate would then be constructed.
- *
- * @param data the DER-encoded PKCS #10 request.
- * @exception IOException for low level errors reading the data
- * @exception SignatureException when the signature is invalid
- * @exception NoSuchAlgorithmException when the signature
- * algorithm is not supported in this environment
- */
- public PKCS10(byte[] data)
- throws IOException, SignatureException, NoSuchAlgorithmException {
- DerInputStream in;
- DerValue[] seq;
- AlgorithmId id;
- byte[] sigData;
- Signature sig;
-
- encoded = data;
-
- //
- // Outer sequence: request, signature algorithm, signature.
- // Parse, and prepare to verify later.
- //
- in = new DerInputStream(data);
- seq = in.getSequence(3);
-
- if (seq.length != 3)
- throw new IllegalArgumentException("not a PKCS #10 request");
-
- data = seq[0].toByteArray(); // reusing this variable
- id = AlgorithmId.parse(seq[1]);
- sigData = seq[2].getBitString();
-
- //
- // Inner sequence: version, name, key, attributes
- //
- BigInteger serial;
- DerValue val;
-
- serial = seq[0].data.getBigInteger();
- if (!serial.equals(BigInteger.ZERO))
- throw new IllegalArgumentException("not PKCS #10 v1");
-
- subject = new X500Name(seq[0].data);
- subjectPublicKeyInfo = X509Key.parse(seq[0].data.getDerValue());
-
- // Cope with a somewhat common illegal PKCS #10 format
- if (seq[0].data.available() != 0)
- attributeSet = new PKCS10Attributes(seq[0].data);
- else
- attributeSet = new PKCS10Attributes();
-
- if (seq[0].data.available() != 0)
- throw new IllegalArgumentException("illegal PKCS #10 data");
-
- //
- // OK, we parsed it all ... validate the signature using the
- // key and signature algorithm we found.
- //
- try {
- sig = Signature.getInstance(id.getName());
- sig.initVerify(subjectPublicKeyInfo);
- sig.update(data);
- if (!sig.verify(sigData))
- throw new SignatureException("Invalid PKCS #10 signature");
- } catch (InvalidKeyException e) {
- throw new SignatureException("invalid key");
- }
- }
-
- /**
- * Create the signed certificate request. This will later be
- * retrieved in either string or binary format.
- *
- * @param subject identifies the signer (by X.500 name).
- * @param signature private key and signing algorithm to use.
- * @exception IOException on errors.
- * @exception CertificateException on certificate handling errors.
- * @exception SignatureException on signature handling errors.
- */
- public void encodeAndSign(X500Name subject, Signature signature)
- throws CertificateException, IOException, SignatureException {
- DerOutputStream out, scratch;
- byte[] certificateRequestInfo;
- byte[] sig;
-
- if (encoded != null)
- throw new SignatureException("request is already signed");
-
- this.subject = subject;
-
- /*
- * Encode cert request info, wrap in a sequence for signing
- */
- scratch = new DerOutputStream();
- scratch.putInteger(BigInteger.ZERO); // PKCS #10 v1.0
- subject.encode(scratch); // X.500 name
- scratch.write(subjectPublicKeyInfo.getEncoded()); // public key
- attributeSet.encode(scratch);
-
- out = new DerOutputStream();
- out.write(DerValue.tag_Sequence, scratch); // wrap it!
- certificateRequestInfo = out.toByteArray();
- scratch = out;
-
- /*
- * Sign it ...
- */
- signature.update(certificateRequestInfo, 0,
- certificateRequestInfo.length);
- sig = signature.sign();
-
- /*
- * Build guts of SIGNED macro
- */
- AlgorithmId algId = null;
- try {
- algId = AlgorithmId.get(signature.getAlgorithm());
- } catch (NoSuchAlgorithmException nsae) {
- throw new SignatureException(nsae);
- }
- algId.encode(scratch); // sig algorithm
- scratch.putBitString(sig); // sig
-
- /*
- * Wrap those guts in a sequence
- */
- out = new DerOutputStream();
- out.write(DerValue.tag_Sequence, scratch);
- encoded = out.toByteArray();
- }
-
- /**
- * Returns the subject's name.
- */
- public X500Name getSubjectName() { return subject; }
-
- /**
- * Returns the subject's public key.
- */
- public PublicKey getSubjectPublicKeyInfo()
- { return subjectPublicKeyInfo; }
-
- /**
- * Returns the additional attributes requested.
- */
- public PKCS10Attributes getAttributes()
- { return attributeSet; }
-
- /**
- * Returns the encoded and signed certificate request as a
- * DER-encoded byte array.
- *
- * @return the certificate request, or null if encodeAndSign()
- * has not yet been called.
- */
- public byte[] getEncoded() {
- if (encoded != null)
- return encoded.clone();
- else
- return null;
- }
-
- /**
- * Prints an E-Mailable version of the certificate request on the print
- * stream passed. The format is a common base64 encoded one, supported
- * by most Certificate Authorities because Netscape web servers have
- * used this for some time. Some certificate authorities expect some
- * more information, in particular contact information for the web
- * server administrator.
- *
- * @param out the print stream where the certificate request
- * will be printed.
- * @exception IOException when an output operation failed
- * @exception SignatureException when the certificate request was
- * not yet signed.
- */
- public void print(PrintStream out)
- throws IOException, SignatureException {
- if (encoded == null)
- throw new SignatureException("Cert request was not signed");
-
- BASE64Encoder encoder = new BASE64Encoder();
-
- out.println("-----BEGIN NEW CERTIFICATE REQUEST-----");
- encoder.encodeBuffer(encoded, out);
- out.println("-----END NEW CERTIFICATE REQUEST-----");
- }
-
- /**
- * Provides a short description of this request.
- */
- public String toString() {
- return "[PKCS #10 certificate request:\n"
- + subjectPublicKeyInfo.toString()
- + " subject: <" + subject + ">" + "\n"
- + " attributes: " + attributeSet.toString()
- + "\n]";
- }
-
- /**
- * Compares this object for equality with the specified
- * object. If the <code>other</code> object is an
- * <code>instanceof</code> <code>PKCS10</code>, then
- * its encoded form is retrieved and compared with the
- * encoded form of this certificate request.
- *
- * @param other the object to test for equality with this object.
- * @return true iff the encoded forms of the two certificate
- * requests match, false otherwise.
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (!(other instanceof PKCS10))
- return false;
- if (encoded == null) // not signed yet
- return false;
- byte[] otherEncoded = ((PKCS10)other).getEncoded();
- if (otherEncoded == null)
- return false;
-
- return java.util.Arrays.equals(encoded, otherEncoded);
- }
-
- /**
- * Returns a hashcode value for this certificate request from its
- * encoded form.
- *
- * @return the hashcode value.
- */
- public int hashCode() {
- int retval = 0;
- if (encoded != null)
- for (int i = 1; i < encoded.length; i++)
- retval += encoded[i] * i;
- return(retval);
- }
-
- private X500Name subject;
- private PublicKey subjectPublicKeyInfo;
- private PKCS10Attributes attributeSet;
- private byte[] encoded; // signed
-}
--- a/jdk/src/share/classes/sun/security/pkcs/PKCS10Attribute.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 1997, 1998, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.pkcs;
-
-import java.io.OutputStream;
-import java.io.IOException;
-
-import sun.security.util.*;
-
-/**
- * Represent a PKCS#10 Attribute.
- *
- * <p>Attributes are additonal information which can be inserted in a PKCS#10
- * certificate request. For example a "Driving License Certificate" could have
- * the driving license number as an attribute.
- *
- * <p>Attributes are represented as a sequence of the attribute identifier
- * (Object Identifier) and a set of DER encoded attribute values.
- *
- * ASN.1 definition of Attribute:
- * <pre>
- * Attribute :: SEQUENCE {
- * type AttributeType,
- * values SET OF AttributeValue
- * }
- * AttributeType ::= OBJECT IDENTIFIER
- * AttributeValue ::= ANY defined by type
- * </pre>
- *
- * @author Amit Kapoor
- * @author Hemma Prafullchandra
- */
-public class PKCS10Attribute implements DerEncoder {
-
- protected ObjectIdentifier attributeId = null;
- protected Object attributeValue = null;
-
- /**
- * Constructs an attribute from a DER encoding.
- * This constructor expects the value to be encoded as defined above,
- * i.e. a SEQUENCE of OID and SET OF value(s), not a literal
- * X.509 v3 extension. Only PKCS9 defined attributes are supported
- * currently.
- *
- * @param derVal the der encoded attribute.
- * @exception IOException on parsing errors.
- */
- public PKCS10Attribute(DerValue derVal) throws IOException {
- PKCS9Attribute attr = new PKCS9Attribute(derVal);
- this.attributeId = attr.getOID();
- this.attributeValue = attr.getValue();
- }
-
- /**
- * Constructs an attribute from individual components of
- * ObjectIdentifier and the value (any java object).
- *
- * @param attributeId the ObjectIdentifier of the attribute.
- * @param attributeValue an instance of a class that implements
- * the attribute identified by the ObjectIdentifier.
- */
- public PKCS10Attribute(ObjectIdentifier attributeId,
- Object attributeValue) {
- this.attributeId = attributeId;
- this.attributeValue = attributeValue;
- }
-
- /**
- * Constructs an attribute from PKCS9 attribute.
- *
- * @param attr the PKCS9Attribute to create from.
- */
- public PKCS10Attribute(PKCS9Attribute attr) {
- this.attributeId = attr.getOID();
- this.attributeValue = attr.getValue();
- }
-
- /**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the OutputStream on which to write the DER encoding.
- *
- * @exception IOException on encoding errors.
- */
- public void derEncode(OutputStream out) throws IOException {
- PKCS9Attribute attr = new PKCS9Attribute(attributeId, attributeValue);
- attr.derEncode(out);
- }
-
- /**
- * Returns the ObjectIdentifier of the attribute.
- */
- public ObjectIdentifier getAttributeId() {
- return (attributeId);
- }
-
- /**
- * Returns the attribute value.
- */
- public Object getAttributeValue() {
- return (attributeValue);
- }
-
- /**
- * Returns the attribute in user readable form.
- */
- public String toString() {
- return (attributeValue.toString());
- }
-}
--- a/jdk/src/share/classes/sun/security/pkcs/PKCS10Attributes.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,219 +0,0 @@
-/*
- * Copyright (c) 1997, 2006, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.pkcs;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.security.cert.CertificateException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import sun.security.util.*;
-
-/**
- * This class defines the PKCS10 attributes for the request.
- * The ASN.1 syntax for this is:
- * <pre>
- * Attributes ::= SET OF Attribute
- * </pre>
- *
- * @author Amit Kapoor
- * @author Hemma Prafullchandra
- * @see PKCS10
- * @see PKCS10Attribute
- */
-public class PKCS10Attributes implements DerEncoder {
-
- private Hashtable<String, PKCS10Attribute> map =
- new Hashtable<String, PKCS10Attribute>(3);
-
- /**
- * Default constructor for the PKCS10 attribute.
- */
- public PKCS10Attributes() { }
-
- /**
- * Create the object from the array of PKCS10Attribute objects.
- *
- * @param attrs the array of PKCS10Attribute objects.
- */
- public PKCS10Attributes(PKCS10Attribute[] attrs) {
- for (int i = 0; i < attrs.length; i++) {
- map.put(attrs[i].getAttributeId().toString(), attrs[i]);
- }
- }
-
- /**
- * Create the object, decoding the values from the passed DER stream.
- * The DER stream contains the SET OF Attribute.
- *
- * @param in the DerInputStream to read the attributes from.
- * @exception IOException on decoding errors.
- */
- public PKCS10Attributes(DerInputStream in) throws IOException {
- DerValue[] attrs = in.getSet(3, true);
-
- if (attrs == null)
- throw new IOException("Illegal encoding of attributes");
- for (int i = 0; i < attrs.length; i++) {
- PKCS10Attribute attr = new PKCS10Attribute(attrs[i]);
- map.put(attr.getAttributeId().toString(), attr);
- }
- }
-
- /**
- * Encode the attributes in DER form to the stream.
- *
- * @param out the OutputStream to marshal the contents to.
- * @exception IOException on encoding errors.
- */
- public void encode(OutputStream out) throws IOException {
- derEncode(out);
- }
-
- /**
- * Encode the attributes in DER form to the stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out the OutputStream to marshal the contents to.
- * @exception IOException on encoding errors.
- */
- public void derEncode(OutputStream out) throws IOException {
- // first copy the elements into an array
- Collection<PKCS10Attribute> allAttrs = map.values();
- PKCS10Attribute[] attribs =
- allAttrs.toArray(new PKCS10Attribute[map.size()]);
-
- DerOutputStream attrOut = new DerOutputStream();
- attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)0),
- attribs);
- out.write(attrOut.toByteArray());
- }
-
- /**
- * Set the attribute value.
- */
- public void setAttribute(String name, Object obj) {
- if (obj instanceof PKCS10Attribute) {
- map.put(name, (PKCS10Attribute)obj);
- }
- }
-
- /**
- * Get the attribute value.
- */
- public Object getAttribute(String name) {
- return map.get(name);
- }
-
- /**
- * Delete the attribute value.
- */
- public void deleteAttribute(String name) {
- map.remove(name);
- }
-
- /**
- * Return an enumeration of names of attributes existing within this
- * attribute.
- */
- public Enumeration<PKCS10Attribute> getElements() {
- return (map.elements());
- }
-
- /**
- * Return a Collection of attributes existing within this
- * PKCS10Attributes object.
- */
- public Collection<PKCS10Attribute> getAttributes() {
- return (Collections.unmodifiableCollection(map.values()));
- }
-
- /**
- * Compares this PKCS10Attributes for equality with the specified
- * object. If the <code>other</code> object is an
- * <code>instanceof</code> <code>PKCS10Attributes</code>, then
- * all the entries are compared with the entries from this.
- *
- * @param other the object to test for equality with this PKCS10Attributes.
- * @return true if all the entries match that of the Other,
- * false otherwise.
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (!(other instanceof PKCS10Attributes))
- return false;
-
- Collection<PKCS10Attribute> othersAttribs =
- ((PKCS10Attributes)other).getAttributes();
- PKCS10Attribute[] attrs =
- othersAttribs.toArray(new PKCS10Attribute[othersAttribs.size()]);
- int len = attrs.length;
- if (len != map.size())
- return false;
- PKCS10Attribute thisAttr, otherAttr;
- String key = null;
- for (int i=0; i < len; i++) {
- otherAttr = attrs[i];
- key = otherAttr.getAttributeId().toString();
-
- if (key == null)
- return false;
- thisAttr = map.get(key);
- if (thisAttr == null)
- return false;
- if (! thisAttr.equals(otherAttr))
- return false;
- }
- return true;
- }
-
- /**
- * Returns a hashcode value for this PKCS10Attributes.
- *
- * @return the hashcode value.
- */
- public int hashCode() {
- return map.hashCode();
- }
-
- /**
- * Returns a string representation of this <tt>PKCS10Attributes</tt> object
- * in the form of a set of entries, enclosed in braces and separated
- * by the ASCII characters "<tt>, </tt>" (comma and space).
- * <p>Overrides the <tt>toString</tt> method of <tt>Object</tt>.
- *
- * @return a string representation of this PKCS10Attributes.
- */
- public String toString() {
- String s = map.size() + "\n" + map.toString();
- return s;
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/pkcs10/PKCS10.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,353 @@
+/*
+ * Copyright (c) 1996, 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+package sun.security.pkcs10;
+
+import java.io.PrintStream;
+import java.io.IOException;
+import java.math.BigInteger;
+
+import java.security.cert.CertificateException;
+import java.security.NoSuchAlgorithmException;
+import java.security.InvalidKeyException;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.PublicKey;
+
+import sun.misc.BASE64Encoder;
+
+import sun.security.util.*;
+import sun.security.x509.AlgorithmId;
+import sun.security.x509.X509Key;
+import sun.security.x509.X500Name;
+
+/**
+ * A PKCS #10 certificate request is created and sent to a Certificate
+ * Authority, which then creates an X.509 certificate and returns it to
+ * the entity that requested it. A certificate request basically consists
+ * of the subject's X.500 name, public key, and optionally some attributes,
+ * signed using the corresponding private key.
+ *
+ * The ASN.1 syntax for a Certification Request is:
+ * <pre>
+ * CertificationRequest ::= SEQUENCE {
+ * certificationRequestInfo CertificationRequestInfo,
+ * signatureAlgorithm SignatureAlgorithmIdentifier,
+ * signature Signature
+ * }
+ *
+ * SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
+ * Signature ::= BIT STRING
+ *
+ * CertificationRequestInfo ::= SEQUENCE {
+ * version Version,
+ * subject Name,
+ * subjectPublicKeyInfo SubjectPublicKeyInfo,
+ * attributes [0] IMPLICIT Attributes
+ * }
+ * Attributes ::= SET OF Attribute
+ * </pre>
+ *
+ * @author David Brownell
+ * @author Amit Kapoor
+ * @author Hemma Prafullchandra
+ */
+public class PKCS10 {
+ /**
+ * Constructs an unsigned PKCS #10 certificate request. Before this
+ * request may be used, it must be encoded and signed. Then it
+ * must be retrieved in some conventional format (e.g. string).
+ *
+ * @param publicKey the public key that should be placed
+ * into the certificate generated by the CA.
+ */
+ public PKCS10(PublicKey publicKey) {
+ subjectPublicKeyInfo = publicKey;
+ attributeSet = new PKCS10Attributes();
+ }
+
+ /**
+ * Constructs an unsigned PKCS #10 certificate request. Before this
+ * request may be used, it must be encoded and signed. Then it
+ * must be retrieved in some conventional format (e.g. string).
+ *
+ * @param publicKey the public key that should be placed
+ * into the certificate generated by the CA.
+ * @param attributes additonal set of PKCS10 attributes requested
+ * for in the certificate.
+ */
+ public PKCS10(PublicKey publicKey, PKCS10Attributes attributes) {
+ subjectPublicKeyInfo = publicKey;
+ attributeSet = attributes;
+ }
+
+ /**
+ * Parses an encoded, signed PKCS #10 certificate request, verifying
+ * the request's signature as it does so. This constructor would
+ * typically be used by a Certificate Authority, from which a new
+ * certificate would then be constructed.
+ *
+ * @param data the DER-encoded PKCS #10 request.
+ * @exception IOException for low level errors reading the data
+ * @exception SignatureException when the signature is invalid
+ * @exception NoSuchAlgorithmException when the signature
+ * algorithm is not supported in this environment
+ */
+ public PKCS10(byte[] data)
+ throws IOException, SignatureException, NoSuchAlgorithmException {
+ DerInputStream in;
+ DerValue[] seq;
+ AlgorithmId id;
+ byte[] sigData;
+ Signature sig;
+
+ encoded = data;
+
+ //
+ // Outer sequence: request, signature algorithm, signature.
+ // Parse, and prepare to verify later.
+ //
+ in = new DerInputStream(data);
+ seq = in.getSequence(3);
+
+ if (seq.length != 3)
+ throw new IllegalArgumentException("not a PKCS #10 request");
+
+ data = seq[0].toByteArray(); // reusing this variable
+ id = AlgorithmId.parse(seq[1]);
+ sigData = seq[2].getBitString();
+
+ //
+ // Inner sequence: version, name, key, attributes
+ //
+ BigInteger serial;
+ DerValue val;
+
+ serial = seq[0].data.getBigInteger();
+ if (!serial.equals(BigInteger.ZERO))
+ throw new IllegalArgumentException("not PKCS #10 v1");
+
+ subject = new X500Name(seq[0].data);
+ subjectPublicKeyInfo = X509Key.parse(seq[0].data.getDerValue());
+
+ // Cope with a somewhat common illegal PKCS #10 format
+ if (seq[0].data.available() != 0)
+ attributeSet = new PKCS10Attributes(seq[0].data);
+ else
+ attributeSet = new PKCS10Attributes();
+
+ if (seq[0].data.available() != 0)
+ throw new IllegalArgumentException("illegal PKCS #10 data");
+
+ //
+ // OK, we parsed it all ... validate the signature using the
+ // key and signature algorithm we found.
+ //
+ try {
+ sig = Signature.getInstance(id.getName());
+ sig.initVerify(subjectPublicKeyInfo);
+ sig.update(data);
+ if (!sig.verify(sigData))
+ throw new SignatureException("Invalid PKCS #10 signature");
+ } catch (InvalidKeyException e) {
+ throw new SignatureException("invalid key");
+ }
+ }
+
+ /**
+ * Create the signed certificate request. This will later be
+ * retrieved in either string or binary format.
+ *
+ * @param subject identifies the signer (by X.500 name).
+ * @param signature private key and signing algorithm to use.
+ * @exception IOException on errors.
+ * @exception CertificateException on certificate handling errors.
+ * @exception SignatureException on signature handling errors.
+ */
+ public void encodeAndSign(X500Name subject, Signature signature)
+ throws CertificateException, IOException, SignatureException {
+ DerOutputStream out, scratch;
+ byte[] certificateRequestInfo;
+ byte[] sig;
+
+ if (encoded != null)
+ throw new SignatureException("request is already signed");
+
+ this.subject = subject;
+
+ /*
+ * Encode cert request info, wrap in a sequence for signing
+ */
+ scratch = new DerOutputStream();
+ scratch.putInteger(BigInteger.ZERO); // PKCS #10 v1.0
+ subject.encode(scratch); // X.500 name
+ scratch.write(subjectPublicKeyInfo.getEncoded()); // public key
+ attributeSet.encode(scratch);
+
+ out = new DerOutputStream();
+ out.write(DerValue.tag_Sequence, scratch); // wrap it!
+ certificateRequestInfo = out.toByteArray();
+ scratch = out;
+
+ /*
+ * Sign it ...
+ */
+ signature.update(certificateRequestInfo, 0,
+ certificateRequestInfo.length);
+ sig = signature.sign();
+
+ /*
+ * Build guts of SIGNED macro
+ */
+ AlgorithmId algId = null;
+ try {
+ algId = AlgorithmId.get(signature.getAlgorithm());
+ } catch (NoSuchAlgorithmException nsae) {
+ throw new SignatureException(nsae);
+ }
+ algId.encode(scratch); // sig algorithm
+ scratch.putBitString(sig); // sig
+
+ /*
+ * Wrap those guts in a sequence
+ */
+ out = new DerOutputStream();
+ out.write(DerValue.tag_Sequence, scratch);
+ encoded = out.toByteArray();
+ }
+
+ /**
+ * Returns the subject's name.
+ */
+ public X500Name getSubjectName() { return subject; }
+
+ /**
+ * Returns the subject's public key.
+ */
+ public PublicKey getSubjectPublicKeyInfo()
+ { return subjectPublicKeyInfo; }
+
+ /**
+ * Returns the additional attributes requested.
+ */
+ public PKCS10Attributes getAttributes()
+ { return attributeSet; }
+
+ /**
+ * Returns the encoded and signed certificate request as a
+ * DER-encoded byte array.
+ *
+ * @return the certificate request, or null if encodeAndSign()
+ * has not yet been called.
+ */
+ public byte[] getEncoded() {
+ if (encoded != null)
+ return encoded.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Prints an E-Mailable version of the certificate request on the print
+ * stream passed. The format is a common base64 encoded one, supported
+ * by most Certificate Authorities because Netscape web servers have
+ * used this for some time. Some certificate authorities expect some
+ * more information, in particular contact information for the web
+ * server administrator.
+ *
+ * @param out the print stream where the certificate request
+ * will be printed.
+ * @exception IOException when an output operation failed
+ * @exception SignatureException when the certificate request was
+ * not yet signed.
+ */
+ public void print(PrintStream out)
+ throws IOException, SignatureException {
+ if (encoded == null)
+ throw new SignatureException("Cert request was not signed");
+
+ BASE64Encoder encoder = new BASE64Encoder();
+
+ out.println("-----BEGIN NEW CERTIFICATE REQUEST-----");
+ encoder.encodeBuffer(encoded, out);
+ out.println("-----END NEW CERTIFICATE REQUEST-----");
+ }
+
+ /**
+ * Provides a short description of this request.
+ */
+ public String toString() {
+ return "[PKCS #10 certificate request:\n"
+ + subjectPublicKeyInfo.toString()
+ + " subject: <" + subject + ">" + "\n"
+ + " attributes: " + attributeSet.toString()
+ + "\n]";
+ }
+
+ /**
+ * Compares this object for equality with the specified
+ * object. If the <code>other</code> object is an
+ * <code>instanceof</code> <code>PKCS10</code>, then
+ * its encoded form is retrieved and compared with the
+ * encoded form of this certificate request.
+ *
+ * @param other the object to test for equality with this object.
+ * @return true iff the encoded forms of the two certificate
+ * requests match, false otherwise.
+ */
+ public boolean equals(Object other) {
+ if (this == other)
+ return true;
+ if (!(other instanceof PKCS10))
+ return false;
+ if (encoded == null) // not signed yet
+ return false;
+ byte[] otherEncoded = ((PKCS10)other).getEncoded();
+ if (otherEncoded == null)
+ return false;
+
+ return java.util.Arrays.equals(encoded, otherEncoded);
+ }
+
+ /**
+ * Returns a hashcode value for this certificate request from its
+ * encoded form.
+ *
+ * @return the hashcode value.
+ */
+ public int hashCode() {
+ int retval = 0;
+ if (encoded != null)
+ for (int i = 1; i < encoded.length; i++)
+ retval += encoded[i] * i;
+ return(retval);
+ }
+
+ private X500Name subject;
+ private PublicKey subjectPublicKeyInfo;
+ private PKCS10Attributes attributeSet;
+ private byte[] encoded; // signed
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/pkcs10/PKCS10Attribute.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 1997, 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.pkcs10;
+
+import java.io.OutputStream;
+import java.io.IOException;
+
+import sun.security.pkcs.PKCS9Attribute;
+import sun.security.util.*;
+
+/**
+ * Represent a PKCS#10 Attribute.
+ *
+ * <p>Attributes are additonal information which can be inserted in a PKCS#10
+ * certificate request. For example a "Driving License Certificate" could have
+ * the driving license number as an attribute.
+ *
+ * <p>Attributes are represented as a sequence of the attribute identifier
+ * (Object Identifier) and a set of DER encoded attribute values.
+ *
+ * ASN.1 definition of Attribute:
+ * <pre>
+ * Attribute :: SEQUENCE {
+ * type AttributeType,
+ * values SET OF AttributeValue
+ * }
+ * AttributeType ::= OBJECT IDENTIFIER
+ * AttributeValue ::= ANY defined by type
+ * </pre>
+ *
+ * @author Amit Kapoor
+ * @author Hemma Prafullchandra
+ */
+public class PKCS10Attribute implements DerEncoder {
+
+ protected ObjectIdentifier attributeId = null;
+ protected Object attributeValue = null;
+
+ /**
+ * Constructs an attribute from a DER encoding.
+ * This constructor expects the value to be encoded as defined above,
+ * i.e. a SEQUENCE of OID and SET OF value(s), not a literal
+ * X.509 v3 extension. Only PKCS9 defined attributes are supported
+ * currently.
+ *
+ * @param derVal the der encoded attribute.
+ * @exception IOException on parsing errors.
+ */
+ public PKCS10Attribute(DerValue derVal) throws IOException {
+ PKCS9Attribute attr = new PKCS9Attribute(derVal);
+ this.attributeId = attr.getOID();
+ this.attributeValue = attr.getValue();
+ }
+
+ /**
+ * Constructs an attribute from individual components of
+ * ObjectIdentifier and the value (any java object).
+ *
+ * @param attributeId the ObjectIdentifier of the attribute.
+ * @param attributeValue an instance of a class that implements
+ * the attribute identified by the ObjectIdentifier.
+ */
+ public PKCS10Attribute(ObjectIdentifier attributeId,
+ Object attributeValue) {
+ this.attributeId = attributeId;
+ this.attributeValue = attributeValue;
+ }
+
+ /**
+ * Constructs an attribute from PKCS9 attribute.
+ *
+ * @param attr the PKCS9Attribute to create from.
+ */
+ public PKCS10Attribute(PKCS9Attribute attr) {
+ this.attributeId = attr.getOID();
+ this.attributeValue = attr.getValue();
+ }
+
+ /**
+ * DER encode this object onto an output stream.
+ * Implements the <code>DerEncoder</code> interface.
+ *
+ * @param out
+ * the OutputStream on which to write the DER encoding.
+ *
+ * @exception IOException on encoding errors.
+ */
+ public void derEncode(OutputStream out) throws IOException {
+ PKCS9Attribute attr = new PKCS9Attribute(attributeId, attributeValue);
+ attr.derEncode(out);
+ }
+
+ /**
+ * Returns the ObjectIdentifier of the attribute.
+ */
+ public ObjectIdentifier getAttributeId() {
+ return (attributeId);
+ }
+
+ /**
+ * Returns the attribute value.
+ */
+ public Object getAttributeValue() {
+ return (attributeValue);
+ }
+
+ /**
+ * Returns the attribute in user readable form.
+ */
+ public String toString() {
+ return (attributeValue.toString());
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/pkcs10/PKCS10Attributes.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 1997, 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.pkcs10;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.security.cert.CertificateException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import sun.security.util.*;
+
+/**
+ * This class defines the PKCS10 attributes for the request.
+ * The ASN.1 syntax for this is:
+ * <pre>
+ * Attributes ::= SET OF Attribute
+ * </pre>
+ *
+ * @author Amit Kapoor
+ * @author Hemma Prafullchandra
+ * @see PKCS10
+ * @see PKCS10Attribute
+ */
+public class PKCS10Attributes implements DerEncoder {
+
+ private Hashtable<String, PKCS10Attribute> map =
+ new Hashtable<String, PKCS10Attribute>(3);
+
+ /**
+ * Default constructor for the PKCS10 attribute.
+ */
+ public PKCS10Attributes() { }
+
+ /**
+ * Create the object from the array of PKCS10Attribute objects.
+ *
+ * @param attrs the array of PKCS10Attribute objects.
+ */
+ public PKCS10Attributes(PKCS10Attribute[] attrs) {
+ for (int i = 0; i < attrs.length; i++) {
+ map.put(attrs[i].getAttributeId().toString(), attrs[i]);
+ }
+ }
+
+ /**
+ * Create the object, decoding the values from the passed DER stream.
+ * The DER stream contains the SET OF Attribute.
+ *
+ * @param in the DerInputStream to read the attributes from.
+ * @exception IOException on decoding errors.
+ */
+ public PKCS10Attributes(DerInputStream in) throws IOException {
+ DerValue[] attrs = in.getSet(3, true);
+
+ if (attrs == null)
+ throw new IOException("Illegal encoding of attributes");
+ for (int i = 0; i < attrs.length; i++) {
+ PKCS10Attribute attr = new PKCS10Attribute(attrs[i]);
+ map.put(attr.getAttributeId().toString(), attr);
+ }
+ }
+
+ /**
+ * Encode the attributes in DER form to the stream.
+ *
+ * @param out the OutputStream to marshal the contents to.
+ * @exception IOException on encoding errors.
+ */
+ public void encode(OutputStream out) throws IOException {
+ derEncode(out);
+ }
+
+ /**
+ * Encode the attributes in DER form to the stream.
+ * Implements the <code>DerEncoder</code> interface.
+ *
+ * @param out the OutputStream to marshal the contents to.
+ * @exception IOException on encoding errors.
+ */
+ public void derEncode(OutputStream out) throws IOException {
+ // first copy the elements into an array
+ Collection<PKCS10Attribute> allAttrs = map.values();
+ PKCS10Attribute[] attribs =
+ allAttrs.toArray(new PKCS10Attribute[map.size()]);
+
+ DerOutputStream attrOut = new DerOutputStream();
+ attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT,
+ true, (byte)0),
+ attribs);
+ out.write(attrOut.toByteArray());
+ }
+
+ /**
+ * Set the attribute value.
+ */
+ public void setAttribute(String name, Object obj) {
+ if (obj instanceof PKCS10Attribute) {
+ map.put(name, (PKCS10Attribute)obj);
+ }
+ }
+
+ /**
+ * Get the attribute value.
+ */
+ public Object getAttribute(String name) {
+ return map.get(name);
+ }
+
+ /**
+ * Delete the attribute value.
+ */
+ public void deleteAttribute(String name) {
+ map.remove(name);
+ }
+
+ /**
+ * Return an enumeration of names of attributes existing within this
+ * attribute.
+ */
+ public Enumeration<PKCS10Attribute> getElements() {
+ return (map.elements());
+ }
+
+ /**
+ * Return a Collection of attributes existing within this
+ * PKCS10Attributes object.
+ */
+ public Collection<PKCS10Attribute> getAttributes() {
+ return (Collections.unmodifiableCollection(map.values()));
+ }
+
+ /**
+ * Compares this PKCS10Attributes for equality with the specified
+ * object. If the <code>other</code> object is an
+ * <code>instanceof</code> <code>PKCS10Attributes</code>, then
+ * all the entries are compared with the entries from this.
+ *
+ * @param other the object to test for equality with this PKCS10Attributes.
+ * @return true if all the entries match that of the Other,
+ * false otherwise.
+ */
+ public boolean equals(Object other) {
+ if (this == other)
+ return true;
+ if (!(other instanceof PKCS10Attributes))
+ return false;
+
+ Collection<PKCS10Attribute> othersAttribs =
+ ((PKCS10Attributes)other).getAttributes();
+ PKCS10Attribute[] attrs =
+ othersAttribs.toArray(new PKCS10Attribute[othersAttribs.size()]);
+ int len = attrs.length;
+ if (len != map.size())
+ return false;
+ PKCS10Attribute thisAttr, otherAttr;
+ String key = null;
+ for (int i=0; i < len; i++) {
+ otherAttr = attrs[i];
+ key = otherAttr.getAttributeId().toString();
+
+ if (key == null)
+ return false;
+ thisAttr = map.get(key);
+ if (thisAttr == null)
+ return false;
+ if (! thisAttr.equals(otherAttr))
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns a hashcode value for this PKCS10Attributes.
+ *
+ * @return the hashcode value.
+ */
+ public int hashCode() {
+ return map.hashCode();
+ }
+
+ /**
+ * Returns a string representation of this <tt>PKCS10Attributes</tt> object
+ * in the form of a set of entries, enclosed in braces and separated
+ * by the ASCII characters "<tt>, </tt>" (comma and space).
+ * <p>Overrides the <tt>toString</tt> method of <tt>Object</tt>.
+ *
+ * @return a string representation of this PKCS10Attributes.
+ */
+ public String toString() {
+ String s = map.size() + "\n" + map.toString();
+ return s;
+ }
+}
--- a/jdk/src/share/classes/sun/security/provider/certpath/CertStoreHelper.java Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/CertStoreHelper.java Thu Oct 13 13:50:17 2011 -0400
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, 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
@@ -27,32 +27,86 @@
import java.net.URI;
import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidAlgorithmParameterException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import java.security.cert.CertStore;
import java.security.cert.X509CertSelector;
import java.security.cert.X509CRLSelector;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
+import sun.security.util.Cache;
+
/**
- * Helper used by URICertStore when delegating to another CertStore to
- * fetch certs and CRLs.
+ * Helper used by URICertStore and others when delegating to another CertStore
+ * to fetch certs and CRLs.
*/
-public interface CertStoreHelper {
+public abstract class CertStoreHelper {
+
+ private static final int NUM_TYPES = 2;
+ private final static Map<String,String> classMap = new HashMap<>(NUM_TYPES);
+ static {
+ classMap.put(
+ "LDAP",
+ "sun.security.provider.certpath.ldap.LDAPCertStoreHelper");
+ classMap.put(
+ "SSLServer",
+ "sun.security.provider.certpath.ssl.SSLServerCertStoreHelper");
+ };
+ private static Cache cache = Cache.newSoftMemoryCache(NUM_TYPES);
+
+ public static CertStoreHelper getInstance(final String type)
+ throws NoSuchAlgorithmException
+ {
+ CertStoreHelper helper = (CertStoreHelper)cache.get(type);
+ if (helper != null) {
+ return helper;
+ }
+ final String cl = classMap.get(type);
+ if (cl == null) {
+ throw new NoSuchAlgorithmException(type + " not available");
+ }
+ try {
+ helper = AccessController.doPrivileged(
+ new PrivilegedExceptionAction<CertStoreHelper>() {
+ public CertStoreHelper run() throws ClassNotFoundException {
+ try {
+ Class<?> c = Class.forName(cl, true, null);
+ CertStoreHelper csh
+ = (CertStoreHelper)c.newInstance();
+ cache.put(type, csh);
+ return csh;
+ } catch (InstantiationException e) {
+ throw new AssertionError(e);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+ });
+ return helper;
+ } catch (PrivilegedActionException e) {
+ throw new NoSuchAlgorithmException(type + " not available",
+ e.getException());
+ }
+ }
/**
* Returns a CertStore using the given URI as parameters.
*/
- CertStore getCertStore(URI uri)
+ public abstract CertStore getCertStore(URI uri)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
/**
* Wraps an existing X509CertSelector when needing to avoid DN matching
* issues.
*/
- X509CertSelector wrap(X509CertSelector selector,
+ public abstract X509CertSelector wrap(X509CertSelector selector,
X500Principal certSubject,
String dn)
throws IOException;
@@ -61,7 +115,7 @@
* Wraps an existing X509CRLSelector when needing to avoid DN matching
* issues.
*/
- X509CRLSelector wrap(X509CRLSelector selector,
+ public abstract X509CRLSelector wrap(X509CRLSelector selector,
Collection<X500Principal> certIssuers,
String dn)
throws IOException;
--- a/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java Thu Oct 13 13:50:17 2011 -0400
@@ -30,8 +30,6 @@
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLConnection;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
@@ -120,36 +118,11 @@
// true if URI is ldap
private boolean ldap = false;
+ private CertStoreHelper ldapHelper;
private CertStore ldapCertStore;
private String ldapPath;
/**
- * Holder class to lazily load LDAPCertStoreHelper if present.
- */
- private static class LDAP {
- private static final String CERT_STORE_HELPER =
- "sun.security.provider.certpath.ldap.LDAPCertStoreHelper";
- private static final CertStoreHelper helper =
- AccessController.doPrivileged(
- new PrivilegedAction<CertStoreHelper>() {
- public CertStoreHelper run() {
- try {
- Class<?> c = Class.forName(CERT_STORE_HELPER, true, null);
- return (CertStoreHelper)c.newInstance();
- } catch (ClassNotFoundException cnf) {
- return null;
- } catch (InstantiationException e) {
- throw new AssertionError(e);
- } catch (IllegalAccessException e) {
- throw new AssertionError(e);
- }
- }});
- static CertStoreHelper helper() {
- return helper;
- }
- }
-
- /**
* Creates a URICertStore.
*
* @param parameters specifying the URI
@@ -164,10 +137,9 @@
this.uri = ((URICertStoreParameters) params).uri;
// if ldap URI, use an LDAPCertStore to fetch certs and CRLs
if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
- if (LDAP.helper() == null)
- throw new NoSuchAlgorithmException("LDAP not present");
ldap = true;
- ldapCertStore = LDAP.helper().getCertStore(uri);
+ ldapHelper = CertStoreHelper.getInstance("LDAP");
+ ldapCertStore = ldapHelper.getCertStore(uri);
ldapPath = uri.getPath();
// strip off leading '/'
if (ldapPath.charAt(0) == '/') {
@@ -251,7 +223,7 @@
if (ldap) {
X509CertSelector xsel = (X509CertSelector) selector;
try {
- xsel = LDAP.helper().wrap(xsel, xsel.getSubject(), ldapPath);
+ xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath);
} catch (IOException ioe) {
throw new CertStoreException(ioe);
}
@@ -273,58 +245,45 @@
return getMatchingCerts(certs, selector);
}
lastChecked = time;
- InputStream in = null;
try {
URLConnection connection = uri.toURL().openConnection();
if (lastModified != 0) {
connection.setIfModifiedSince(lastModified);
}
- in = connection.getInputStream();
long oldLastModified = lastModified;
- lastModified = connection.getLastModified();
- if (oldLastModified != 0) {
- if (oldLastModified == lastModified) {
- if (debug != null) {
- debug.println("Not modified, using cached copy");
- }
- return getMatchingCerts(certs, selector);
- } else if (connection instanceof HttpURLConnection) {
- // some proxy servers omit last modified
- HttpURLConnection hconn = (HttpURLConnection) connection;
- if (hconn.getResponseCode()
- == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ try (InputStream in = connection.getInputStream()) {
+ lastModified = connection.getLastModified();
+ if (oldLastModified != 0) {
+ if (oldLastModified == lastModified) {
if (debug != null) {
debug.println("Not modified, using cached copy");
}
return getMatchingCerts(certs, selector);
+ } else if (connection instanceof HttpURLConnection) {
+ // some proxy servers omit last modified
+ HttpURLConnection hconn = (HttpURLConnection)connection;
+ if (hconn.getResponseCode()
+ == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ if (debug != null) {
+ debug.println("Not modified, using cached copy");
+ }
+ return getMatchingCerts(certs, selector);
+ }
}
}
- }
- if (debug != null) {
- debug.println("Downloading new certificates...");
+ if (debug != null) {
+ debug.println("Downloading new certificates...");
+ }
+ // Safe cast since factory is an X.509 certificate factory
+ certs = (Collection<X509Certificate>)
+ factory.generateCertificates(in);
}
- // Safe cast since factory is an X.509 certificate factory
- certs = (Collection<X509Certificate>)
- factory.generateCertificates(in);
return getMatchingCerts(certs, selector);
- } catch (IOException e) {
+ } catch (IOException | CertificateException e) {
if (debug != null) {
debug.println("Exception fetching certificates:");
e.printStackTrace();
}
- } catch (CertificateException e) {
- if (debug != null) {
- debug.println("Exception fetching certificates:");
- e.printStackTrace();
- }
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- // ignore
- }
- }
}
// exception, forget previous values
lastModified = 0;
@@ -343,8 +302,7 @@
if (selector == null) {
return certs;
}
- List<X509Certificate> matchedCerts =
- new ArrayList<X509Certificate>(certs.size());
+ List<X509Certificate> matchedCerts = new ArrayList<>(certs.size());
for (X509Certificate cert : certs) {
if (selector.match(cert)) {
matchedCerts.add(cert);
@@ -374,7 +332,7 @@
if (ldap) {
X509CRLSelector xsel = (X509CRLSelector) selector;
try {
- xsel = LDAP.helper().wrap(xsel, null, ldapPath);
+ xsel = ldapHelper.wrap(xsel, null, ldapPath);
} catch (IOException ioe) {
throw new CertStoreException(ioe);
}
@@ -395,56 +353,43 @@
return getMatchingCRLs(crl, selector);
}
lastChecked = time;
- InputStream in = null;
try {
URLConnection connection = uri.toURL().openConnection();
if (lastModified != 0) {
connection.setIfModifiedSince(lastModified);
}
- in = connection.getInputStream();
long oldLastModified = lastModified;
- lastModified = connection.getLastModified();
- if (oldLastModified != 0) {
- if (oldLastModified == lastModified) {
- if (debug != null) {
- debug.println("Not modified, using cached copy");
- }
- return getMatchingCRLs(crl, selector);
- } else if (connection instanceof HttpURLConnection) {
- // some proxy servers omit last modified
- HttpURLConnection hconn = (HttpURLConnection) connection;
- if (hconn.getResponseCode()
- == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ try (InputStream in = connection.getInputStream()) {
+ lastModified = connection.getLastModified();
+ if (oldLastModified != 0) {
+ if (oldLastModified == lastModified) {
if (debug != null) {
debug.println("Not modified, using cached copy");
}
return getMatchingCRLs(crl, selector);
+ } else if (connection instanceof HttpURLConnection) {
+ // some proxy servers omit last modified
+ HttpURLConnection hconn = (HttpURLConnection)connection;
+ if (hconn.getResponseCode()
+ == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ if (debug != null) {
+ debug.println("Not modified, using cached copy");
+ }
+ return getMatchingCRLs(crl, selector);
+ }
}
}
- }
- if (debug != null) {
- debug.println("Downloading new CRL...");
+ if (debug != null) {
+ debug.println("Downloading new CRL...");
+ }
+ crl = (X509CRL) factory.generateCRL(in);
}
- crl = (X509CRL) factory.generateCRL(in);
return getMatchingCRLs(crl, selector);
- } catch (IOException e) {
+ } catch (IOException | CRLException e) {
if (debug != null) {
debug.println("Exception fetching CRL:");
e.printStackTrace();
}
- } catch (CRLException e) {
- if (debug != null) {
- debug.println("Exception fetching CRL:");
- e.printStackTrace();
- }
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- // ignore
- }
- }
}
// exception, forget previous values
lastModified = 0;
--- a/jdk/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java Thu Oct 13 13:50:17 2011 -0400
@@ -103,7 +103,7 @@
* @author Steve Hanna
* @author Andreas Sterbenz
*/
-public class LDAPCertStore extends CertStoreSpi {
+public final class LDAPCertStore extends CertStoreSpi {
private static final Debug debug = Debug.getInstance("certpath");
--- a/jdk/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java Thu Oct 13 13:50:17 2011 -0400
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, 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
@@ -41,11 +41,9 @@
* LDAP implementation of CertStoreHelper.
*/
-public class LDAPCertStoreHelper
- implements CertStoreHelper
+public final class LDAPCertStoreHelper
+ extends CertStoreHelper
{
- public LDAPCertStoreHelper() { }
-
@Override
public CertStore getCertStore(URI uri)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStore.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.provider.certpath.ssl;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.Provider;
+import java.security.cert.CertificateException;
+import java.security.cert.CertSelector;
+import java.security.cert.CertStore;
+import java.security.cert.CertStoreException;
+import java.security.cert.CertStoreParameters;
+import java.security.cert.CertStoreSpi;
+import java.security.cert.CRLSelector;
+import java.security.cert.X509Certificate;
+import java.security.cert.X509CRL;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+/**
+ * A CertStore that retrieves an SSL server's certificate chain.
+ */
+public final class SSLServerCertStore extends CertStoreSpi {
+
+ private final URI uri;
+
+ SSLServerCertStore(URI uri) throws InvalidAlgorithmParameterException {
+ super(null);
+ this.uri = uri;
+ }
+
+ public synchronized Collection<X509Certificate> engineGetCertificates
+ (CertSelector selector) throws CertStoreException
+ {
+ try {
+ SSLContext sc = SSLContext.getInstance("SSL");
+ GetChainTrustManager xtm = new GetChainTrustManager();
+ sc.init(null, new TrustManager[] { xtm }, null);
+ HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+ HttpsURLConnection.setDefaultHostnameVerifier(
+ new HostnameVerifier() {
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ });
+ uri.toURL().openConnection().connect();
+ return getMatchingCerts(xtm.serverChain, selector);
+ } catch (GeneralSecurityException | IOException e) {
+ throw new CertStoreException(e);
+ }
+ }
+
+ private static List<X509Certificate> getMatchingCerts
+ (List<X509Certificate> certs, CertSelector selector)
+ {
+ // if selector not specified, all certs match
+ if (selector == null) {
+ return certs;
+ }
+ List<X509Certificate> matchedCerts = new ArrayList<>(certs.size());
+ for (X509Certificate cert : certs) {
+ if (selector.match(cert)) {
+ matchedCerts.add(cert);
+ }
+ }
+ return matchedCerts;
+ }
+
+ public Collection<X509CRL> engineGetCRLs(CRLSelector selector)
+ throws CertStoreException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ static synchronized CertStore getInstance(URI uri)
+ throws InvalidAlgorithmParameterException
+ {
+ return new CS(new SSLServerCertStore(uri), null, "SSLServer", null);
+ }
+
+ /*
+ * An X509TrustManager that simply stores a reference to the server's
+ * certificate chain.
+ */
+ private static class GetChainTrustManager implements X509TrustManager {
+ private List<X509Certificate> serverChain;
+
+ public X509Certificate[] getAcceptedIssuers() {
+ throw new UnsupportedOperationException();
+ }
+
+ public void checkClientTrusted(X509Certificate[] chain,
+ String authType)
+ throws CertificateException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain,
+ String authType)
+ throws CertificateException
+ {
+ this.serverChain = (chain == null)
+ ? Collections.<X509Certificate>emptyList()
+ : Arrays.asList(chain);
+ }
+ }
+
+ /**
+ * This class allows the SSLServerCertStore to be accessed as a CertStore.
+ */
+ private static class CS extends CertStore {
+ protected CS(CertStoreSpi spi, Provider p, String type,
+ CertStoreParameters params)
+ {
+ super(spi, p, type, params);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.provider.certpath.ssl;
+
+import java.net.URI;
+import java.util.Collection;
+import java.security.NoSuchAlgorithmException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.cert.CertStore;
+import java.security.cert.X509CertSelector;
+import java.security.cert.X509CRLSelector;
+import javax.security.auth.x500.X500Principal;
+import java.io.IOException;
+
+import sun.security.provider.certpath.CertStoreHelper;
+
+/**
+ * SSL implementation of CertStoreHelper.
+ */
+public final class SSLServerCertStoreHelper extends CertStoreHelper {
+
+ @Override
+ public CertStore getCertStore(URI uri)
+ throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
+ {
+ return SSLServerCertStore.getInstance(uri);
+ }
+
+ @Override
+ public X509CertSelector wrap(X509CertSelector selector,
+ X500Principal certSubject,
+ String ldapDN)
+ throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public X509CRLSelector wrap(X509CRLSelector selector,
+ Collection<X500Principal> certIssuers,
+ String ldapDN)
+ throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/tools/CertAndKeyGen.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) 1996, 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.tools;
+
+import java.io.IOException;
+import java.security.cert.X509Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateEncodingException;
+import java.security.*;
+import java.util.Date;
+
+import sun.security.pkcs10.PKCS10;
+import sun.security.x509.AlgorithmId;
+import sun.security.x509.CertificateAlgorithmId;
+import sun.security.x509.CertificateIssuerName;
+import sun.security.x509.CertificateSerialNumber;
+import sun.security.x509.CertificateSubjectName;
+import sun.security.x509.CertificateValidity;
+import sun.security.x509.CertificateVersion;
+import sun.security.x509.CertificateX509Key;
+import sun.security.x509.X500Name;
+import sun.security.x509.X509CertImpl;
+import sun.security.x509.X509CertInfo;
+import sun.security.x509.X509Key;
+
+
+/**
+ * Generate a pair of keys, and provide access to them. This class is
+ * provided primarily for ease of use.
+ *
+ * <P>This provides some simple certificate management functionality.
+ * Specifically, it allows you to create self-signed X.509 certificates
+ * as well as PKCS 10 based certificate signing requests.
+ *
+ * <P>Keys for some public key signature algorithms have algorithm
+ * parameters, such as DSS/DSA. Some sites' Certificate Authorities
+ * adopt fixed algorithm parameters, which speeds up some operations
+ * including key generation and signing. <em>At this time, this interface
+ * does not provide a way to provide such algorithm parameters, e.g.
+ * by providing the CA certificate which includes those parameters.</em>
+ *
+ * <P>Also, note that at this time only signature-capable keys may be
+ * acquired through this interface. Diffie-Hellman keys, used for secure
+ * key exchange, may be supported later.
+ *
+ * @author David Brownell
+ * @author Hemma Prafullchandra
+ * @see PKCS10
+ * @see X509CertImpl
+ */
+public final class CertAndKeyGen {
+ /**
+ * Creates a CertAndKeyGen object for a particular key type
+ * and signature algorithm.
+ *
+ * @param keyType type of key, e.g. "RSA", "DSA"
+ * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
+ * "MD2WithRSA", "SHAwithDSA".
+ * @exception NoSuchAlgorithmException on unrecognized algorithms.
+ */
+ public CertAndKeyGen (String keyType, String sigAlg)
+ throws NoSuchAlgorithmException
+ {
+ keyGen = KeyPairGenerator.getInstance(keyType);
+ this.sigAlg = sigAlg;
+ }
+
+ /**
+ * Creates a CertAndKeyGen object for a particular key type,
+ * signature algorithm, and provider.
+ *
+ * @param keyType type of key, e.g. "RSA", "DSA"
+ * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
+ * "MD2WithRSA", "SHAwithDSA".
+ * @param providerName name of the provider
+ * @exception NoSuchAlgorithmException on unrecognized algorithms.
+ * @exception NoSuchProviderException on unrecognized providers.
+ */
+ public CertAndKeyGen (String keyType, String sigAlg, String providerName)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ if (providerName == null) {
+ keyGen = KeyPairGenerator.getInstance(keyType);
+ } else {
+ try {
+ keyGen = KeyPairGenerator.getInstance(keyType, providerName);
+ } catch (Exception e) {
+ // try first available provider instead
+ keyGen = KeyPairGenerator.getInstance(keyType);
+ }
+ }
+ this.sigAlg = sigAlg;
+ }
+
+ /**
+ * Sets the source of random numbers used when generating keys.
+ * If you do not provide one, a system default facility is used.
+ * You may wish to provide your own source of random numbers
+ * to get a reproducible sequence of keys and signatures, or
+ * because you may be able to take advantage of strong sources
+ * of randomness/entropy in your environment.
+ */
+ public void setRandom (SecureRandom generator)
+ {
+ prng = generator;
+ }
+
+ // want "public void generate (X509Certificate)" ... inherit DSA/D-H param
+
+ /**
+ * Generates a random public/private key pair, with a given key
+ * size. Different algorithms provide different degrees of security
+ * for the same key size, because of the "work factor" involved in
+ * brute force attacks. As computers become faster, it becomes
+ * easier to perform such attacks. Small keys are to be avoided.
+ *
+ * <P>Note that not all values of "keyBits" are valid for all
+ * algorithms, and not all public key algorithms are currently
+ * supported for use in X.509 certificates. If the algorithm
+ * you specified does not produce X.509 compatible keys, an
+ * invalid key exception is thrown.
+ *
+ * @param keyBits the number of bits in the keys.
+ * @exception InvalidKeyException if the environment does not
+ * provide X.509 public keys for this signature algorithm.
+ */
+ public void generate (int keyBits)
+ throws InvalidKeyException
+ {
+ KeyPair pair;
+
+ try {
+ if (prng == null) {
+ prng = new SecureRandom();
+ }
+ keyGen.initialize(keyBits, prng);
+ pair = keyGen.generateKeyPair();
+
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e.getMessage());
+ }
+
+ publicKey = pair.getPublic();
+ privateKey = pair.getPrivate();
+ }
+
+
+ /**
+ * Returns the public key of the generated key pair if it is of type
+ * <code>X509Key</code>, or null if the public key is of a different type.
+ *
+ * XXX Note: This behaviour is needed for backwards compatibility.
+ * What this method really should return is the public key of the
+ * generated key pair, regardless of whether or not it is an instance of
+ * <code>X509Key</code>. Accordingly, the return type of this method
+ * should be <code>PublicKey</code>.
+ */
+ public X509Key getPublicKey()
+ {
+ if (!(publicKey instanceof X509Key)) {
+ return null;
+ }
+ return (X509Key)publicKey;
+ }
+
+
+ /**
+ * Returns the private key of the generated key pair.
+ *
+ * <P><STRONG><em>Be extremely careful when handling private keys.
+ * When private keys are not kept secret, they lose their ability
+ * to securely authenticate specific entities ... that is a huge
+ * security risk!</em></STRONG>
+ */
+ public PrivateKey getPrivateKey ()
+ {
+ return privateKey;
+ }
+
+
+ /**
+ * Returns a self-signed X.509v3 certificate for the public key.
+ * The certificate is immediately valid. No extensions.
+ *
+ * <P>Such certificates normally are used to identify a "Certificate
+ * Authority" (CA). Accordingly, they will not always be accepted by
+ * other parties. However, such certificates are also useful when
+ * you are bootstrapping your security infrastructure, or deploying
+ * system prototypes.
+ *
+ * @param myname X.500 name of the subject (who is also the issuer)
+ * @param firstDate the issue time of the certificate
+ * @param validity how long the certificate should be valid, in seconds
+ * @exception CertificateException on certificate handling errors.
+ * @exception InvalidKeyException on key handling errors.
+ * @exception SignatureException on signature handling errors.
+ * @exception NoSuchAlgorithmException on unrecognized algorithms.
+ * @exception NoSuchProviderException on unrecognized providers.
+ */
+ public X509Certificate getSelfCertificate (
+ X500Name myname, Date firstDate, long validity)
+ throws CertificateException, InvalidKeyException, SignatureException,
+ NoSuchAlgorithmException, NoSuchProviderException
+ {
+ X509CertImpl cert;
+ Date lastDate;
+
+ try {
+ lastDate = new Date ();
+ lastDate.setTime (firstDate.getTime () + validity * 1000);
+
+ CertificateValidity interval =
+ new CertificateValidity(firstDate,lastDate);
+
+ X509CertInfo info = new X509CertInfo();
+ // Add all mandatory attributes
+ info.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
+ info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
+ new java.util.Random().nextInt() & 0x7fffffff));
+ AlgorithmId algID = AlgorithmId.get(sigAlg);
+ info.set(X509CertInfo.ALGORITHM_ID,
+ new CertificateAlgorithmId(algID));
+ info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname));
+ info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
+ info.set(X509CertInfo.VALIDITY, interval);
+ info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname));
+
+ cert = new X509CertImpl(info);
+ cert.sign(privateKey, this.sigAlg);
+
+ return (X509Certificate)cert;
+
+ } catch (IOException e) {
+ throw new CertificateEncodingException("getSelfCert: " +
+ e.getMessage());
+ }
+ }
+
+ // Keep the old method
+ public X509Certificate getSelfCertificate (X500Name myname, long validity)
+ throws CertificateException, InvalidKeyException, SignatureException,
+ NoSuchAlgorithmException, NoSuchProviderException
+ {
+ return getSelfCertificate(myname, new Date(), validity);
+ }
+
+ /**
+ * Returns a PKCS #10 certificate request. The caller uses either
+ * <code>PKCS10.print</code> or <code>PKCS10.toByteArray</code>
+ * operations on the result, to get the request in an appropriate
+ * transmission format.
+ *
+ * <P>PKCS #10 certificate requests are sent, along with some proof
+ * of identity, to Certificate Authorities (CAs) which then issue
+ * X.509 public key certificates.
+ *
+ * @param myname X.500 name of the subject
+ * @exception InvalidKeyException on key handling errors.
+ * @exception SignatureException on signature handling errors.
+ */
+ public PKCS10 getCertRequest (X500Name myname)
+ throws InvalidKeyException, SignatureException
+ {
+ PKCS10 req = new PKCS10 (publicKey);
+
+ try {
+ Signature signature = Signature.getInstance(sigAlg);
+ signature.initSign (privateKey);
+ req.encodeAndSign(myname, signature);
+
+ } catch (CertificateException e) {
+ throw new SignatureException (sigAlg + " CertificateException");
+
+ } catch (IOException e) {
+ throw new SignatureException (sigAlg + " IOException");
+
+ } catch (NoSuchAlgorithmException e) {
+ // "can't happen"
+ throw new SignatureException (sigAlg + " unavailable?");
+ }
+ return req;
+ }
+
+ private SecureRandom prng;
+ private String sigAlg;
+ private KeyPairGenerator keyGen;
+ private PublicKey publicKey;
+ private PrivateKey privateKey;
+}
--- a/jdk/src/share/classes/sun/security/tools/KeyTool.java Wed Sep 28 15:10:02 2011 -0700
+++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java Thu Oct 13 13:50:17 2011 -0400
@@ -38,10 +38,12 @@
import java.security.Timestamp;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
+import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
+import java.security.cert.CertStoreException;
import java.security.cert.CRL;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
@@ -63,23 +65,16 @@
import javax.security.auth.x500.X500Principal;
import sun.misc.BASE64Encoder;
import sun.security.util.ObjectIdentifier;
-import sun.security.pkcs.PKCS10;
+import sun.security.pkcs10.PKCS10;
+import sun.security.pkcs10.PKCS10Attribute;
import sun.security.provider.X509Factory;
+import sun.security.provider.certpath.CertStoreHelper;
import sun.security.util.Password;
-import sun.security.util.PathList;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
import sun.misc.BASE64Decoder;
-import sun.security.pkcs.PKCS10Attribute;
import sun.security.pkcs.PKCS9Attribute;
-import sun.security.provider.certpath.ldap.LDAPCertStoreHelper;
import sun.security.util.DerValue;
import sun.security.x509.*;
@@ -917,18 +912,13 @@
// Perform the specified command
if (command == CERTREQ) {
- PrintStream ps = null;
if (filename != null) {
- ps = new PrintStream(new FileOutputStream
- (filename));
- out = ps;
- }
- try {
+ try (PrintStream ps = new PrintStream(new FileOutputStream
+ (filename))) {
+ doCertReq(alias, sigAlgName, ps);
+ }
+ } else {
doCertReq(alias, sigAlgName, out);
- } finally {
- if (ps != null) {
- ps.close();
- }
}
if (verbose && filename != null) {
MessageFormat form = new MessageFormat(rb.getString
@@ -941,18 +931,13 @@
doDeleteEntry(alias);
kssave = true;
} else if (command == EXPORTCERT) {
- PrintStream ps = null;
if (filename != null) {
- ps = new PrintStream(new FileOutputStream
- (filename));
- out = ps;
- }
- try {
+ try (PrintStream ps = new PrintStream(new FileOutputStream
+ (filename))) {
+ doExportCert(alias, ps);
+ }
+ } else {
doExportCert(alias, out);
- } finally {
- if (ps != null) {
- ps.close();
- }
}
if (filename != null) {
MessageFormat form = new MessageFormat(rb.getString
@@ -973,16 +958,12 @@
doGenSecretKey(alias, keyAlgName, keysize);
kssave = true;
} else if (command == IDENTITYDB) {
- InputStream inStream = System.in;
if (filename != null) {
- inStream = new FileInputStream(filename);
- }
- try {
- doImportIdentityDatabase(inStream);
- } finally {
- if (inStream != System.in) {
- inStream.close();
+ try (InputStream inStream = new FileInputStream(filename)) {
+ doImportIdentityDatabase(inStream);
}
+ } else {
+ doImportIdentityDatabase(System.in);
}
} else if (command == IMPORTCERT) {
InputStream inStream = System.in;
@@ -1101,29 +1082,21 @@
if (alias == null) {
alias = keyAlias;
}
- PrintStream ps = null;
if (filename != null) {
- ps = new PrintStream(new FileOutputStream(filename));
- out = ps;
- }
- try {
+ try (PrintStream ps =
+ new PrintStream(new FileOutputStream(filename))) {
+ doGenCRL(ps);
+ }
+ } else {
doGenCRL(out);
- } finally {
- if (ps != null) {
- ps.close();
- }
}
} else if (command == PRINTCERTREQ) {
- InputStream inStream = System.in;
if (filename != null) {
- inStream = new FileInputStream(filename);
- }
- try {
- doPrintCertReq(inStream, out);
- } finally {
- if (inStream != System.in) {
- inStream.close();
+ try (InputStream inStream = new FileInputStream(filename)) {
+ doPrintCertReq(inStream, out);
}
+ } else {
+ doPrintCertReq(System.in, out);
}
} else if (command == PRINTCRL) {
doPrintCRL(filename, out);
@@ -2070,12 +2043,13 @@
}
}
} else { // must be LDAP, and uri is not null
+ // Lazily load LDAPCertStoreHelper if present
+ CertStoreHelper helper = CertStoreHelper.getInstance("LDAP");
String path = uri.getPath();
if (path.charAt(0) == '/') path = path.substring(1);
- LDAPCertStoreHelper h = new LDAPCertStoreHelper();
- CertStore s = h.getCertStore(uri);
+ CertStore s = helper.getCertStore(uri);
X509CRLSelector sel =
- h.wrap(new X509CRLSelector(), null, path);
+ helper.wrap(new X509CRLSelector(), null, path);
return s.getCRLs(sel);
}
}
@@ -2259,18 +2233,12 @@
int pos = 0;
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
- InputStream is = null;
- try {
- is = jf.getInputStream(je);
+ try (InputStream is = jf.getInputStream(je)) {
while (is.read(buffer) != -1) {
// we just read. this will throw a SecurityException
// if a signature/digest check fails. This also
// populate the signers
}
- } finally {
- if (is != null) {
- is.close();
- }
}
CodeSigner[] signers = je.getCodeSigners();
if (signers != null) {
@@ -2316,85 +2284,52 @@
out.println(rb.getString("Not.a.signed.jar.file"));
}
} else if (sslserver != null) {
- SSLContext sc = SSLContext.getInstance("SSL");
- final boolean[] certPrinted = new boolean[1];
- sc.init(null, new TrustManager[] {
- new X509TrustManager() {
-
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- public void checkClientTrusted(
- java.security.cert.X509Certificate[] certs, String authType) {
+ // Lazily load SSLCertStoreHelper if present
+ CertStoreHelper helper = CertStoreHelper.getInstance("SSLServer");
+ CertStore cs = helper.getCertStore(new URI("https://" + sslserver));
+ Collection<? extends Certificate> chain;
+ try {
+ chain = cs.getCertificates(null);
+ if (chain.isEmpty()) {
+ // If the certs are not retrieved, we consider it an error
+ // even if the URL connection is successful.
+ throw new Exception(rb.getString(
+ "No.certificate.from.the.SSL.server"));
+ }
+ } catch (CertStoreException cse) {
+ if (cse.getCause() instanceof IOException) {
+ throw new Exception(rb.getString(
+ "No.certificate.from.the.SSL.server"),
+ cse.getCause());
+ } else {
+ throw cse;
+ }
+ }
+
+ int i = 0;
+ for (Certificate cert : chain) {
+ try {
+ if (rfc) {
+ dumpCert(cert, out);
+ } else {
+ out.println("Certificate #" + i++);
+ out.println("====================================");
+ printX509Cert((X509Certificate)cert, out);
+ out.println();
}
-
- public void checkServerTrusted(
- java.security.cert.X509Certificate[] certs, String authType) {
- for (int i=0; i<certs.length; i++) {
- X509Certificate cert = certs[i];
- try {
- if (rfc) {
- dumpCert(cert, out);
- } else {
- out.println("Certificate #" + i);
- out.println("====================================");
- printX509Cert(cert, out);
- out.println();
- }
- } catch (Exception e) {
- if (debug) {
- e.printStackTrace();
- }
- }
- }
-
- // Set to true where there's something to print
- if (certs.length > 0) {
- certPrinted[0] = true;
- }
+ } catch (Exception e) {
+ if (debug) {
+ e.printStackTrace();
}
}
- }, null);
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- HttpsURLConnection.setDefaultHostnameVerifier(
- new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- });
- // HTTPS instead of raw SSL, so that -Dhttps.proxyHost and
- // -Dhttps.proxyPort can be used. Since we only go through
- // the handshake process, an HTTPS server is not needed.
- // This program should be able to deal with any SSL-based
- // network service.
- Exception ex = null;
- try {
- new URL("https://" + sslserver).openConnection().connect();
- } catch (Exception e) {
- ex = e;
- }
- // If the certs are not printed out, we consider it an error even
- // if the URL connection is successful.
- if (!certPrinted[0]) {
- Exception e = new Exception(
- rb.getString("No.certificate.from.the.SSL.server"));
- if (ex != null) {
- e.initCause(ex);
- }
- throw e;
}
} else {
- InputStream inStream = System.in;
if (filename != null) {
- inStream = new FileInputStream(filename);
- }
- try {
- printCertFromStream(inStream, out);
- } finally {
- if (inStream != System.in) {
- inStream.close();
+ try (FileInputStream inStream = new FileInputStream(filename)) {
+ printCertFromStream(inStream, out);
}
+ } else {
+ printCertFromStream(System.in, out);
}
}
}
@@ -2590,9 +2525,7 @@
X509Certificate cert = null;
try {
cert = (X509Certificate)cf.generateCertificate(in);
- } catch (ClassCastException cce) {
- throw new Exception(rb.getString("Input.not.an.X.509.certificate"));
- } catch (CertificateException ce) {
+ } catch (ClassCastException | CertificateException ce) {
throw new Exception(rb.getString("Input.not.an.X.509.certificate"));
}
@@ -3441,16 +3374,10 @@
if (!file.exists()) {
return null;
}
- FileInputStream fis = null;
KeyStore caks = null;
- try {
- fis = new FileInputStream(file);
+ try (FileInputStream fis = new FileInputStream(file)) {
caks = KeyStore.getInstance(JKS);
caks.load(fis, null);
- } finally {
- if (fis != null) {
- fis.close();
- }
}
return caks;
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/tools/PathList.java Thu Oct 13 13:50:17 2011 -0400
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2004, 2011, 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.tools;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.String;
+import java.util.StringTokenizer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.MalformedURLException;
+
+/**
+ * A utility class for handle path list
+ *
+ */
+public class PathList {
+ /**
+ * Utility method for appending path from pathFrom to pathTo.
+ *
+ * @param pathTo the target path
+ * @param pathSource the path to be appended to pathTo
+ * @return the resulting path
+ */
+ public static String appendPath(String pathTo, String pathFrom) {
+ if (pathTo == null || pathTo.length() == 0) {
+ return pathFrom;
+ } else if (pathFrom == null || pathFrom.length() == 0) {
+ return pathTo;
+ } else {
+ return pathTo + File.pathSeparator + pathFrom;
+ }
+ }
+
+ /**
+ * Utility method for converting a search path string to an array
+ * of directory and JAR file URLs.
+ *
+ * @param path the search path string
+ * @return the resulting array of directory and JAR file URLs
+ */
+ public static URL[] pathToURLs(String path) {
+ StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
+ URL[] urls = new URL[st.countTokens()];
+ int count = 0;
+ while (st.hasMoreTokens()) {
+ URL url = fileToURL(new File(st.nextToken()));
+ if (url != null) {
+ urls[count++] = url;
+ }
+ }
+ if (urls.length != count) {
+ URL[] tmp = new URL[count];
+ System.arraycopy(urls, 0, tmp, 0, count);
+ urls = tmp;
+ }
+ return urls;
+ }
+
+ /**
+ * Returns the directory or JAR file URL corresponding to the specified
+ * local file name.
+ *
+ * @param file the File object
+ * @return the resulting directory or JAR file URL, or null if unknown
+ */
+ private static URL fileToURL(File file) {
+ String name;
+ try {
+ name = file.getCanonicalPath();
+ } catch (IOException e) {
+ name = file.getAbsolutePath();
+ }
+ name = name.replace(File.separatorChar, '/');
+ if (!name.startsWith("/")) {
+ name = "/" + name;
+ }
+ // If the file does not exist, then assume that it's a directory
+ if (!file.isFile()) {
+ name = name + "/";
+ }
+ try {
+ return new URL("file", "", name);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException("file");
+ }
+ }
+}
--- a/jdk/src/share/classes/sun/security/util/BigInt.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,198 +0,0 @@
-/*
- * Copyright (c) 1996, 2006, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.util;
-
-import java.math.BigInteger;
-
-
-/**
- * A low-overhead arbitrary-precision <em>unsigned</em> integer.
- * This is intended for use with ASN.1 parsing, and printing of
- * such parsed values. Convert to "BigInteger" if you need to do
- * arbitrary precision arithmetic, rather than just represent
- * the number as a wrapped array of bytes.
- *
- * <P><em><b>NOTE:</b> This class may eventually disappear, to
- * be supplanted by big-endian byte arrays which hold both signed
- * and unsigned arbitrary-precision integers.</em>
- *
- * @author David Brownell
- */
-public final class BigInt {
-
- // Big endian -- MSB first.
- private byte[] places;
-
- /**
- * Constructs a "Big" integer from a set of (big-endian) bytes.
- * Leading zeroes should be stripped off.
- *
- * @param data a sequence of bytes, most significant bytes/digits
- * first. CONSUMED.
- */
- public BigInt(byte[] data) { places = data.clone(); }
-
- /**
- * Constructs a "Big" integer from a "BigInteger", which must be
- * positive (or zero) in value.
- */
- public BigInt(BigInteger i) {
- byte[] temp = i.toByteArray();
-
- if ((temp[0] & 0x80) != 0)
- throw new IllegalArgumentException("negative BigInteger");
-
- // XXX we assume exactly _one_ sign byte is used...
-
- if (temp[0] != 0)
- places = temp;
- else {
- places = new byte[temp.length - 1];
- for (int j = 1; j < temp.length; j++)
- places[j - 1] = temp[j];
- }
- }
-
- /**
- * Constructs a "Big" integer from a normal Java integer.
- *
- * @param i the java primitive integer
- */
- public BigInt(int i) {
- if (i < (1 << 8)) {
- places = new byte[1];
- places[0] = (byte) i;
- } else if (i < (1 << 16)) {
- places = new byte[2];
- places[0] = (byte) (i >> 8);
- places[1] = (byte) i;
- } else if (i < (1 << 24)) {
- places = new byte[3];
- places[0] = (byte) (i >> 16);
- places[1] = (byte) (i >> 8);
- places[2] = (byte) i;
- } else {
- places = new byte[4];
- places[0] = (byte) (i >> 24);
- places[1] = (byte) (i >> 16);
- places[2] = (byte) (i >> 8);
- places[3] = (byte) i;
- }
- }
-
- /**
- * Converts the "big" integer to a java primitive integer.
- *
- * @excpet NumberFormatException if 32 bits is insufficient.
- */
- public int toInt() {
- if (places.length > 4)
- throw new NumberFormatException("BigInt.toLong, too big");
- int retval = 0, i = 0;
- for (; i < places.length; i++)
- retval = (retval << 8) + ((int)places[i] & 0xff);
- return retval;
- }
-
- /**
- * Returns a hexadecimal printed representation. The value is
- * formatted to fit on lines of at least 75 characters, with
- * embedded newlines. Words are separated for readability,
- * with eight words (32 bytes) per line.
- */
- public String toString() { return hexify(); }
-
- /**
- * Returns a BigInteger value which supports many arithmetic
- * operations. Assumes negative values will never occur.
- */
- public BigInteger toBigInteger()
- { return new BigInteger(1, places); }
-
- /**
- * Returns the data as a byte array. The most significant bit
- * of the array is bit zero (as in <code>java.math.BigInteger</code>).
- */
- public byte[] toByteArray() { return places.clone(); }
-
- private static final String digits = "0123456789abcdef";
- private String hexify() {
- if (places.length == 0)
- return " 0 ";
-
- StringBuffer buf = new StringBuffer(places.length * 2);
- buf.append(" "); // four spaces
- for (int i = 0; i < places.length; i++) {
- buf.append(digits.charAt((places[i] >> 4) & 0x0f));
- buf.append(digits.charAt(places[i] & 0x0f));
- if (((i + 1) % 32) == 0) {
- if ((i + 1) != places.length)
- buf.append("\n "); // line after four words
- } else if (((i + 1) % 4) == 0)
- buf.append(' '); // space between words
- }
- return buf.toString();
- }
-
- /**
- * Returns true iff the parameter is a numerically equivalent
- * BigInt.
- *
- * @param other the object being compared with this one.
- */
- public boolean equals(Object other) {
- if (other instanceof BigInt)
- return equals((BigInt) other);
- return false;
- }
-
- /**
- * Returns true iff the parameter is numerically equivalent.
- *
- * @param other the BigInt being compared with this one.
- */
- public boolean equals(BigInt other) {
- if (this == other)
- return true;
-
- byte[] otherPlaces = other.toByteArray();
- if (places.length != otherPlaces.length)
- return false;
- for (int i = 0; i < places.length; i++)
- if (places[i] != otherPlaces[i])
- return false;
- return true;
- }
-
- /**
- * Returns a hashcode for this BigInt.
- *
- * @return a hashcode for this BigInt.
- */
- public int hashCode() {
- return hexify().hashCode();
- }
-}
--- a/jdk/src/share/classes/sun/security/util/PathList.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,111 +0,0 @@
-/*
- * Copyright (c) 2004, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.util;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.String;
-import java.util.StringTokenizer;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.MalformedURLException;
-
-/**
- * A utility class for handle path list
- *
- */
-public class PathList {
- /**
- * Utility method for appending path from pathFrom to pathTo.
- *
- * @param pathTo the target path
- * @param pathSource the path to be appended to pathTo
- * @return the resulting path
- */
- public static String appendPath(String pathTo, String pathFrom) {
- if (pathTo == null || pathTo.length() == 0) {
- return pathFrom;
- } else if (pathFrom == null || pathFrom.length() == 0) {
- return pathTo;
- } else {
- return pathTo + File.pathSeparator + pathFrom;
- }
- }
-
- /**
- * Utility method for converting a search path string to an array
- * of directory and JAR file URLs.
- *
- * @param path the search path string
- * @return the resulting array of directory and JAR file URLs
- */
- public static URL[] pathToURLs(String path) {
- StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
- URL[] urls = new URL[st.countTokens()];
- int count = 0;
- while (st.hasMoreTokens()) {
- URL url = fileToURL(new File(st.nextToken()));
- if (url != null) {
- urls[count++] = url;
- }
- }
- if (urls.length != count) {
- URL[] tmp = new URL[count];
- System.arraycopy(urls, 0, tmp, 0, count);
- urls = tmp;
- }
- return urls;
- }
-
- /**
- * Returns the directory or JAR file URL corresponding to the specified
- * local file name.
- *
- * @param file the File object
- * @return the resulting directory or JAR file URL, or null if unknown
- */
- private static URL fileToURL(File file) {
- String name;
- try {
- name = file.getCanonicalPath();
- } catch (IOException e) {
- name = file.getAbsolutePath();
- }
- name = name.replace(File.separatorChar, '/');
- if (!name.startsWith("/")) {
- name = "/" + name;
- }
- // If the file does not exist, then assume that it's a directory
- if (!file.isFile()) {
- name = name + "/";
- }
- try {
- return new URL("file", "", name);
- } catch (MalformedURLException e) {
- throw new IllegalArgumentException("file");
- }
- }
-}
--- a/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,301 +0,0 @@
-/*
- * Copyright (c) 1996, 2011, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.x509;
-
-import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateEncodingException;
-import java.security.*;
-import java.util.Date;
-
-import sun.security.pkcs.PKCS10;
-
-
-/**
- * Generate a pair of keys, and provide access to them. This class is
- * provided primarily for ease of use.
- *
- * <P>This provides some simple certificate management functionality.
- * Specifically, it allows you to create self-signed X.509 certificates
- * as well as PKCS 10 based certificate signing requests.
- *
- * <P>Keys for some public key signature algorithms have algorithm
- * parameters, such as DSS/DSA. Some sites' Certificate Authorities
- * adopt fixed algorithm parameters, which speeds up some operations
- * including key generation and signing. <em>At this time, this interface
- * does not provide a way to provide such algorithm parameters, e.g.
- * by providing the CA certificate which includes those parameters.</em>
- *
- * <P>Also, note that at this time only signature-capable keys may be
- * acquired through this interface. Diffie-Hellman keys, used for secure
- * key exchange, may be supported later.
- *
- * @author David Brownell
- * @author Hemma Prafullchandra
- * @see PKCS10
- * @see X509CertImpl
- */
-public final class CertAndKeyGen {
- /**
- * Creates a CertAndKeyGen object for a particular key type
- * and signature algorithm.
- *
- * @param keyType type of key, e.g. "RSA", "DSA"
- * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
- * "MD2WithRSA", "SHAwithDSA".
- * @exception NoSuchAlgorithmException on unrecognized algorithms.
- */
- public CertAndKeyGen (String keyType, String sigAlg)
- throws NoSuchAlgorithmException
- {
- keyGen = KeyPairGenerator.getInstance(keyType);
- this.sigAlg = sigAlg;
- }
-
- /**
- * Creates a CertAndKeyGen object for a particular key type,
- * signature algorithm, and provider.
- *
- * @param keyType type of key, e.g. "RSA", "DSA"
- * @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
- * "MD2WithRSA", "SHAwithDSA".
- * @param providerName name of the provider
- * @exception NoSuchAlgorithmException on unrecognized algorithms.
- * @exception NoSuchProviderException on unrecognized providers.
- */
- public CertAndKeyGen (String keyType, String sigAlg, String providerName)
- throws NoSuchAlgorithmException, NoSuchProviderException
- {
- if (providerName == null) {
- keyGen = KeyPairGenerator.getInstance(keyType);
- } else {
- try {
- keyGen = KeyPairGenerator.getInstance(keyType, providerName);
- } catch (Exception e) {
- // try first available provider instead
- keyGen = KeyPairGenerator.getInstance(keyType);
- }
- }
- this.sigAlg = sigAlg;
- }
-
- /**
- * Sets the source of random numbers used when generating keys.
- * If you do not provide one, a system default facility is used.
- * You may wish to provide your own source of random numbers
- * to get a reproducible sequence of keys and signatures, or
- * because you may be able to take advantage of strong sources
- * of randomness/entropy in your environment.
- */
- public void setRandom (SecureRandom generator)
- {
- prng = generator;
- }
-
- // want "public void generate (X509Certificate)" ... inherit DSA/D-H param
-
- /**
- * Generates a random public/private key pair, with a given key
- * size. Different algorithms provide different degrees of security
- * for the same key size, because of the "work factor" involved in
- * brute force attacks. As computers become faster, it becomes
- * easier to perform such attacks. Small keys are to be avoided.
- *
- * <P>Note that not all values of "keyBits" are valid for all
- * algorithms, and not all public key algorithms are currently
- * supported for use in X.509 certificates. If the algorithm
- * you specified does not produce X.509 compatible keys, an
- * invalid key exception is thrown.
- *
- * @param keyBits the number of bits in the keys.
- * @exception InvalidKeyException if the environment does not
- * provide X.509 public keys for this signature algorithm.
- */
- public void generate (int keyBits)
- throws InvalidKeyException
- {
- KeyPair pair;
-
- try {
- if (prng == null) {
- prng = new SecureRandom();
- }
- keyGen.initialize(keyBits, prng);
- pair = keyGen.generateKeyPair();
-
- } catch (Exception e) {
- throw new IllegalArgumentException(e.getMessage());
- }
-
- publicKey = pair.getPublic();
- privateKey = pair.getPrivate();
- }
-
-
- /**
- * Returns the public key of the generated key pair if it is of type
- * <code>X509Key</code>, or null if the public key is of a different type.
- *
- * XXX Note: This behaviour is needed for backwards compatibility.
- * What this method really should return is the public key of the
- * generated key pair, regardless of whether or not it is an instance of
- * <code>X509Key</code>. Accordingly, the return type of this method
- * should be <code>PublicKey</code>.
- */
- public X509Key getPublicKey()
- {
- if (!(publicKey instanceof X509Key)) {
- return null;
- }
- return (X509Key)publicKey;
- }
-
-
- /**
- * Returns the private key of the generated key pair.
- *
- * <P><STRONG><em>Be extremely careful when handling private keys.
- * When private keys are not kept secret, they lose their ability
- * to securely authenticate specific entities ... that is a huge
- * security risk!</em></STRONG>
- */
- public PrivateKey getPrivateKey ()
- {
- return privateKey;
- }
-
-
- /**
- * Returns a self-signed X.509v3 certificate for the public key.
- * The certificate is immediately valid. No extensions.
- *
- * <P>Such certificates normally are used to identify a "Certificate
- * Authority" (CA). Accordingly, they will not always be accepted by
- * other parties. However, such certificates are also useful when
- * you are bootstrapping your security infrastructure, or deploying
- * system prototypes.
- *
- * @param myname X.500 name of the subject (who is also the issuer)
- * @param firstDate the issue time of the certificate
- * @param validity how long the certificate should be valid, in seconds
- * @exception CertificateException on certificate handling errors.
- * @exception InvalidKeyException on key handling errors.
- * @exception SignatureException on signature handling errors.
- * @exception NoSuchAlgorithmException on unrecognized algorithms.
- * @exception NoSuchProviderException on unrecognized providers.
- */
- public X509Certificate getSelfCertificate (
- X500Name myname, Date firstDate, long validity)
- throws CertificateException, InvalidKeyException, SignatureException,
- NoSuchAlgorithmException, NoSuchProviderException
- {
- X509CertImpl cert;
- Date lastDate;
-
- try {
- lastDate = new Date ();
- lastDate.setTime (firstDate.getTime () + validity * 1000);
-
- CertificateValidity interval =
- new CertificateValidity(firstDate,lastDate);
-
- X509CertInfo info = new X509CertInfo();
- // Add all mandatory attributes
- info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
- info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
- new java.util.Random().nextInt() & 0x7fffffff));
- AlgorithmId algID = AlgorithmId.get(sigAlg);
- info.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(algID));
- info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname));
- info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
- info.set(X509CertInfo.VALIDITY, interval);
- info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname));
-
- cert = new X509CertImpl(info);
- cert.sign(privateKey, this.sigAlg);
-
- return (X509Certificate)cert;
-
- } catch (IOException e) {
- throw new CertificateEncodingException("getSelfCert: " +
- e.getMessage());
- }
- }
-
- // Keep the old method
- public X509Certificate getSelfCertificate (X500Name myname, long validity)
- throws CertificateException, InvalidKeyException, SignatureException,
- NoSuchAlgorithmException, NoSuchProviderException
- {
- return getSelfCertificate(myname, new Date(), validity);
- }
-
- /**
- * Returns a PKCS #10 certificate request. The caller uses either
- * <code>PKCS10.print</code> or <code>PKCS10.toByteArray</code>
- * operations on the result, to get the request in an appropriate
- * transmission format.
- *
- * <P>PKCS #10 certificate requests are sent, along with some proof
- * of identity, to Certificate Authorities (CAs) which then issue
- * X.509 public key certificates.
- *
- * @param myname X.500 name of the subject
- * @exception InvalidKeyException on key handling errors.
- * @exception SignatureException on signature handling errors.
- */
- public PKCS10 getCertRequest (X500Name myname)
- throws InvalidKeyException, SignatureException
- {
- PKCS10 req = new PKCS10 (publicKey);
-
- try {
- Signature signature = Signature.getInstance(sigAlg);
- signature.initSign (privateKey);
- req.encodeAndSign(myname, signature);
-
- } catch (CertificateException e) {
- throw new SignatureException (sigAlg + " CertificateException");
-
- } catch (IOException e) {
- throw new SignatureException (sigAlg + " IOException");
-
- } catch (NoSuchAlgorithmException e) {
- // "can't happen"
- throw new SignatureException (sigAlg + " unavailable?");
- }
- return req;
- }
-
- private SecureRandom prng;
- private String sigAlg;
- private KeyPairGenerator keyGen;
- private PublicKey publicKey;
- private PrivateKey privateKey;
-}
--- a/jdk/test/sun/security/util/BigInt/BigIntEqualsHashCode.java Wed Sep 28 15:10:02 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 1999, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @author Gary Ellison
- * @bug 4170635
- * @summary Verify equals()/hashCode() contract honored
- */
-
-import java.io.*;
-import sun.security.util.*;
-
-
-public class BigIntEqualsHashCode {
- public static void main(String[] args) throws Exception {
- BigInt bi1 = new BigInt(12345678);
- BigInt bi2 = new BigInt(12345678);
-
- if ( (bi1.equals(bi2)) == (bi1.hashCode()==bi2.hashCode()) )
- System.out.println("PASSED");
- else
- throw new Exception ("FAILED equals()/hashCode() contract");
-
- }
-}