x509certimpl.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,815 行 · 第 1/5 页

JAVA
1,815
字号
/* * @(#)X509CertImpl.java	1.5 06/10/10 * * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved.   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER   *    * This program 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 program 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 at /legal/license.txt).    *    * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa   * Clara, CA 95054 or visit www.sun.com if you need additional   * information or have any questions.  * *//* * Note that there are two versions of X509CertImpl, this * subsetted one for CDC/FP and another for the security optional * package. Be sure you're editing the right one! */package sun.security.x509;import java.io.BufferedReader;import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.math.BigInteger;import java.security.*;import java.security.cert.*;import java.security.cert.Certificate;import java.util.*;import javax.security.auth.x500.X500Principal;import sun.misc.HexDumpEncoder;import sun.misc.BASE64Decoder;import sun.security.util.*;import sun.security.provider.X509Factory;/** * The X509CertImpl class represents an X.509 certificate. These certificates * are widely used to support authentication and other functionality in * Internet security systems.  Common applications include Privacy Enhanced * Mail (PEM), Transport Layer Security (SSL), code signing for trusted * software distribution, and Secure Electronic Transactions (SET).  There * is a commercial infrastructure ready to manage large scale deployments * of X.509 identity certificates. * * <P>These certificates are managed and vouched for by <em>Certificate * Authorities</em> (CAs).  CAs are services which create certificates by * placing data in the X.509 standard format and then digitally signing * that data.  Such signatures are quite difficult to forge.  CAs act as * trusted third parties, making introductions between agents who have no * direct knowledge of each other.  CA certificates are either signed by * themselves, or by some other CA such as a "root" CA. * * <P>RFC 1422 is very informative, though it does not describe much * of the recent work being done with X.509 certificates.  That includes * a 1996 version (X.509v3) and a variety of enhancements being made to * facilitate an explosion of personal certificates used as "Internet * Drivers' Licences", or with SET for credit card transactions. * * <P>More recent work includes the IETF PKIX Working Group efforts, * especially RFC2459. * * @author Dave Brownell * @author Amit Kapoor * @author Hemma Prafullchandra * @version 1.109 02/02/00 * @see X509CertInfo */public class X509CertImpl extends X509Certificate implements DerEncoder {    private static final String DOT = ".";    /**     * Public attribute names.     */    public static final String NAME = "x509";    public static final String INFO = X509CertInfo.NAME;    public static final String ALG_ID = "algorithm";    public static final String SIGNATURE = "signature";    public static final String SIGNED_CERT = "signed_cert";    /**     * The following are defined for ease-of-use. These     * are the most frequently retrieved attributes.     */    // x509.info.subject.dname    public static final String SUBJECT_DN = NAME + DOT + INFO + DOT +                               X509CertInfo.SUBJECT + DOT +                               CertificateSubjectName.DN_NAME;    // x509.info.issuer.dname    public static final String ISSUER_DN = NAME + DOT + INFO + DOT +                               X509CertInfo.ISSUER + DOT +                               CertificateIssuerName.DN_NAME;    // x509.info.serialNumber.number    public static final String SERIAL_ID = NAME + DOT + INFO + DOT +                               X509CertInfo.SERIAL_NUMBER + DOT +                               CertificateSerialNumber.NUMBER;    // x509.info.key.value    public static final String PUBLIC_KEY = NAME + DOT + INFO + DOT +                               X509CertInfo.KEY + DOT +                               CertificateX509Key.KEY;    // x509.info.version.value    public static final String VERSION = NAME + DOT + INFO + DOT +	                       X509CertInfo.VERSION + DOT +                               CertificateVersion.VERSION;    // x509.algorithm    public static final String SIG_ALG = NAME + DOT + ALG_ID;    // x509.signature    public static final String SIG = NAME + DOT + SIGNATURE;    // when we sign and decode we set this to true    // this is our means to make certificates immutable    private boolean readOnly = false;    // Certificate data, and its envelope    private byte[] 		signedCert = null;    protected X509CertInfo	info = null;    protected AlgorithmId	algId = null;    protected byte[]		signature = null;    // recognized extension OIDS    private static final String KEY_USAGE_OID = "2.5.29.15";    private static final String EXTENDED_KEY_USAGE_OID = "2.5.29.37";    private static final String BASIC_CONSTRAINT_OID = "2.5.29.19";    private static final String SUBJECT_ALT_NAME_OID = "2.5.29.17";    private static final String ISSUER_ALT_NAME_OID = "2.5.29.18";    // number of standard key usage bits.    private static final int NUM_STANDARD_KEY_USAGE = 9;    // SubjectAlterntativeNames cache    private Collection subjectAlternativeNames;    // IssuerAlternativeNames cache    private Collection issuerAlternativeNames;    // ExtendedKeyUsage cache    private List extKeyUsage;    /**     * PublicKey that has previously been used to verify     * the signature of this certificate. Null if the certificate has not      * yet been verified.     */    private PublicKey verifiedPublicKey;    /**     * If verifiedPublicKey is not null, name of the provider used to     * successfully verify the signature of this certificate, or the     * empty String if no provider was explicitly specified.     */    private String verifiedProvider;    /**     * If verifiedPublicKey is not null, result of the verification using     * verifiedPublicKey and verifiedProvider. If true, verification was     * successful, if false, it failed.     */    private boolean verificationResult;        /**     * Default constructor.     */    public X509CertImpl() { }    /**     * Unmarshals a certificate from its encoded form, parsing the     * encoded bytes.  This form of constructor is used by agents which     * need to examine and use certificate contents.  That is, this is     * one of the more commonly used constructors.  Note that the buffer     * must include only a certificate, and no "garbage" may be left at     * the end.  If you need to ignore data at the end of a certificate,     * use another constructor.     *     * @param certData the encoded bytes, with no trailing padding.     * @exception CertificateException on parsing and initialization errors.     */    public X509CertImpl(byte[] certData) throws CertificateException {        try {            parse(new DerValue(certData));        } catch (IOException e) {            signedCert = null;	    CertificateException ce = new 		CertificateException("Unable to initialize, " + e);	    ce.initCause(e);	    throw ce;        }    }    /**     * unmarshals an X.509 certificate from an input stream.  If the     * certificate is RFC1421 hex-encoded, then it must begin with     * the line X509Factory.BEGIN_CERT and end with the line     * X509Factory.END_CERT.     *     * @param in an input stream holding at least one certificate that may     *        be either DER-encoded or RFC1421 hex-encoded version of the     *        DER-encoded certificate.     * @exception CertificateException on parsing and initialization errors.     */    public X509CertImpl(InputStream in) throws CertificateException {	DerValue der = null;	BufferedInputStream inBuffered = new BufferedInputStream(in);	// First try reading stream as HEX-encoded DER-encoded bytes, 	// since not mistakable for raw DER	try {	    inBuffered.mark(Integer.MAX_VALUE);	    der = readRFC1421Cert(inBuffered);	} catch (IOException ioe) {	    try {		// Next, try reading stream as raw DER-encoded bytes		inBuffered.reset();		der = new DerValue(inBuffered);	    } catch (IOException ioe1) {		CertificateException ce = new 		    CertificateException("Input stream must be " +				         "either DER-encoded bytes " +					 "or RFC1421 hex-encoded " +					 "DER-encoded bytes: " +					 ioe1.getMessage());		ce.initCause(ioe1);		throw ce;	    }	}        try {            parse(der);        } catch (IOException ioe) {            signedCert = null;            CertificateException ce = new 		CertificateException("Unable to parse DER value of " +				     "certificate, " + ioe);	    ce.initCause(ioe);	    throw ce;        }    }    /**     * read input stream as HEX-encoded DER-encoded bytes     *     * @param in InputStream to read     * @returns DerValue corresponding to decoded HEX-encoded bytes     * @throws IOException if stream can not be interpreted as RFC1421      *                     encoded bytes     */    private DerValue readRFC1421Cert(InputStream in) throws IOException {	DerValue der = null;	String line = null;	BufferedReader certBufferedReader =	                   new BufferedReader(new InputStreamReader(in));	try {	    line = certBufferedReader.readLine();	} catch (IOException ioe1) {	    throw new IOException("Unable to read InputStream: " +				  ioe1.getMessage());	}	if (line.equals(X509Factory.BEGIN_CERT)) {	    /* stream appears to be hex-encoded bytes */	    BASE64Decoder         decoder   = new BASE64Decoder();	    ByteArrayOutputStream decstream = new ByteArrayOutputStream();	    try {		while ((line = certBufferedReader.readLine()) != null) {		    if (line.equals(X509Factory.END_CERT)) {			der = new DerValue(decstream.toByteArray());			break;		    } else {			decstream.write(decoder.decodeBuffer(line));		    }		}	    } catch (IOException ioe2) {		throw new IOException("Unable to read InputStream: " 				      + ioe2.getMessage());	    }	} else {	    throw new IOException("InputStream is not RFC1421 hex-encoded " +				  "DER bytes");	}	return der;    }    /**     * Construct an initialized X509 Certificate. The certificate is stored     * in raw form and has to be signed to be useful.     *        * @params info the X509CertificateInfo which the Certificate is to be     *              created from.     */    public X509CertImpl(X509CertInfo certInfo) {        this.info = certInfo;    }    /**     * Unmarshal a certificate from its encoded form, parsing a DER value.     * This form of constructor is used by agents which need to examine     * and use certificate contents.     *        * @param derVal the der value containing the encoded cert.     * @exception CertificateException on parsing and initialization errors.     */      public X509CertImpl(DerValue derVal) throws CertificateException {        try {            parse(derVal);        } catch (IOException e) {            signedCert = null;            CertificateException ce = new 		CertificateException("Unable to initialize, " + e);	    ce.initCause(e);	    throw ce;        }    }    /**     * Appends the certificate to an output stream.     *     * @param out an input stream to which the certificate is appended.     * @exception CertificateEncodingException on encoding errors.     */    public void encode(OutputStream out)    throws CertificateEncodingException {        if (signedCert == null)            throw new CertificateEncodingException(                          "Null certificate to encode");        try {            out.write((byte[])signedCert.clone());        } catch (IOException e) {            throw new CertificateEncodingException(e.toString());        }    }    /**     * DER encode this object onto an output stream.     * Implements the <code>DerEncoder</code> interface.     *     * @param out the output stream on which to write the DER encoding.     *     * @exception IOException on encoding error.     */    public void derEncode(OutputStream out) throws IOException {        if (signedCert == null)            throw new IOException("Null certificate to encode");	out.write((byte[])signedCert.clone());    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?