⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 certtools.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/************************************************************************* *                                                                       * *  EJBCA: The OpenSource Certificate Authority                          * *                                                                       * *  This software is free software; you can redistribute it and/or       * *  modify it under the terms of the GNU Lesser General Public           * *  License as published by the Free Software Foundation; either         * *  version 2.1 of the License, or any later version.                    * *                                                                       * *  See terms of license at gnu.org.                                     * *                                                                       * *************************************************************************/ package org.ejbca.util;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintStream;import java.math.BigInteger;import java.net.URL;import java.security.InvalidKeyException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.SecureRandom;import java.security.Security;import java.security.SignatureException;import java.security.cert.CRLException;import java.security.cert.Certificate;import java.security.cert.CertificateEncodingException;import java.security.cert.CertificateException;import java.security.cert.CertificateFactory;import java.security.cert.CertificateParsingException;import java.security.cert.X509CRL;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.Collection;import java.util.Date;import java.util.Hashtable;import java.util.Iterator;import java.util.List;import java.util.Vector;import org.apache.commons.lang.BooleanUtils;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import org.bouncycastle.asn1.ASN1EncodableVector;import org.bouncycastle.asn1.ASN1InputStream;import org.bouncycastle.asn1.ASN1OctetString;import org.bouncycastle.asn1.ASN1Sequence;import org.bouncycastle.asn1.ASN1TaggedObject;import org.bouncycastle.asn1.DERBitString;import org.bouncycastle.asn1.DEREncodable;import org.bouncycastle.asn1.DERIA5String;import org.bouncycastle.asn1.DERObject;import org.bouncycastle.asn1.DERObjectIdentifier;import org.bouncycastle.asn1.DEROctetString;import org.bouncycastle.asn1.DERSequence;import org.bouncycastle.asn1.DERTaggedObject;import org.bouncycastle.asn1.DERUTF8String;import org.bouncycastle.asn1.x509.AccessDescription;import org.bouncycastle.asn1.x509.AuthorityInformationAccess;import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;import org.bouncycastle.asn1.x509.BasicConstraints;import org.bouncycastle.asn1.x509.GeneralName;import org.bouncycastle.asn1.x509.GeneralNames;import org.bouncycastle.asn1.x509.PolicyInformation;import org.bouncycastle.asn1.x509.ReasonFlags;import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;import org.bouncycastle.asn1.x509.X509DefaultEntryConverter;import org.bouncycastle.asn1.x509.X509Extensions;import org.bouncycastle.asn1.x509.X509Name;import org.bouncycastle.asn1.x509.X509NameEntryConverter;import org.bouncycastle.asn1.x509.X509NameTokenizer;import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;import org.bouncycastle.jce.X509KeyUsage;import org.bouncycastle.jce.interfaces.ConfigurableProvider;import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.bouncycastle.math.ec.ECCurve;import org.bouncycastle.util.encoders.Hex;import org.bouncycastle.x509.X509V3CertificateGenerator;import org.ejbca.core.model.ca.crl.RevokedCertInfo;import org.ejbca.util.dn.DNFieldExtractor;import org.ejbca.util.dn.DnComponents;/** * Tools to handle common certificate operations. * * @version $Id: CertTools.java,v 1.35.2.3 2007/06/05 13:36:33 anatom Exp $ */public class CertTools {    private static Logger log = Logger.getLogger(CertTools.class);        // Initialize dnComponents    static {        DnComponents.getDnObjects();    }    public static final String EMAIL = "rfc822name";    public static final String EMAIL1 = "email";    public static final String EMAIL2 = "EmailAddress";    public static final String EMAIL3 = "E";    public static final String DNS = "dNSName";    public static final String URI = "uniformResourceIdentifier";    public static final String URI1 = "uri";    public static final String URI2 = "uniformResourceId";    public static final String IPADDR = "iPAddress";    public static final String DIRECTORYNAME = "directoryName";    /** Microsoft altName for windows smart card logon */    public static final String UPN = "upn";    /** ObjectID for upn altName for windows smart card logon */    public static final String UPN_OBJECTID = "1.3.6.1.4.1.311.20.2.3";    /** Microsoft altName for windows domain controller guid */    public static final String GUID = "guid";    /** ObjectID for upn altName for windows domain controller guid */    public static final String GUID_OBJECTID = "1.3.6.1.4.1.311.25.1";    /** Object id id-pkix */    public static final String id_pkix = "1.3.6.1.5.5.7";    /** Object id id-pda */    public static final String id_pda = id_pkix + ".9";    /** Object id id-pda-dateOfBirth      * DateOfBirth ::= GeneralizedTime     */    public static final String id_pda_dateOfBirth = id_pda + ".1";     /** Object id id-pda-placeOfBirth      * PlaceOfBirth ::= DirectoryString      */    public static final String id_pda_placeOfBirth = id_pda + ".2";     /** Object id id-pda-gender     *  Gender ::= PrintableString (SIZE(1))     *          -- "M", "F", "m" or "f"     */    public static final String id_pda_gender = id_pda + ".3";     /** Object id id-pda-countryOfCitizenship     * CountryOfCitizenship ::= PrintableString (SIZE (2))     *                      -- ISO 3166 Country Code      */    public static final String id_pda_countryOfCitizenship = id_pda + ".4";     /** Object id id-pda-countryOfResidence     * CountryOfResidence ::= PrintableString (SIZE (2))     *                    -- ISO 3166 Country Code      */    public static final String id_pda_countryOfResidence = id_pda + ".5";     /** Object id for qcStatements Extension */    public static final String QCSTATEMENTS_OBJECTID = "1.3.6.1.5.5.7.1.3";    /** OID used for creating MS Templates */    public static final String OID_MSTEMPLATE = "1.3.6.1.4.1.311.20.2";                  private static final String[] EMAILIDS = { EMAIL, EMAIL1, EMAIL2, EMAIL3 };    /** ObjectID for unstructuredName DN attribute */    //public static final DERObjectIdentifier unstructuredName = new DERObjectIdentifier("1.2.840.113549.1.9.2");    /** ObjectID for unstructuredAddress DN attribute */    //public static final DERObjectIdentifier unstructuredAddress = new DERObjectIdentifier("1.2.840.113549.1.9.8");    /** Parameters used when generating or verifying ECDSA keys/certs using the "implicitlyCA" key encoding.     * The curve parameters is then defined outside of the key and configured in the BC provider.     */    private static String IMPLICITLYCA_Q = "@ecdsa.implicitlyca.q@";    private static String IMPLICITLYCA_A = "@ecdsa.implicitlyca.a@";     private static String IMPLICITLYCA_B = "@ecdsa.implicitlyca.b@";     private static String IMPLICITLYCA_G = "@ecdsa.implicitlyca.g@";     private static String IMPLICITLYCA_N = "@ecdsa.implicitlyca.n@";    /** Flag indicating if the BC provider should be removed before installing it again. When developing and re-deploying alot     * this is needed so you don't have to restart JBoss all the time.      * In production it may cause failures because the BC provider may get removed just when another thread wants to use it.     * Therefore the default value is false.      */    private static final boolean developmentProviderInstallation = BooleanUtils.toBoolean("@development.provider.installation@");        /**     * inhibits creation of new CertTools     */    protected CertTools() {    }    /** See stringToBcX509Name(String, X509NameEntryConverter), this method uses the default BC converter (X509DefaultEntryConverter)     * @see #stringToBcX509Name(String, X509NameEntryConverter)     * @param dn     * @param dn     *          String containing DN that will be transformed into X509Name, The     *          DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in     *          the string will be added to the end positions of OID array.     *      * @return X509Name or null if input is null     */    public static X509Name stringToBcX509Name(String dn) {    	X509NameEntryConverter converter = new X509DefaultEntryConverter();    	return stringToBcX509Name(dn, converter);    	    	    }    /**     * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID     * (with order) are:     * <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU,     * O, L, ST, DC, C </code>     * To change order edit 'dnObjects' in this source file. Important NOT to mess     * with the ordering within this class, since cert vierification on some     * clients (IE :-() might depend on order.     *      * @param dn     *          String containing DN that will be transformed into X509Name, The     *          DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in     *          the string will be added to the end positions of OID array.     * @param converter BC converter for DirectoryStrings, that determines which encoding is chosen     * @return X509Name or null if input is null     */    public static X509Name stringToBcX509Name(String dn, X509NameEntryConverter converter) {      //log.debug(">stringToBcX509Name: " + dn);      if (dn == null)        return null;      Vector defaultOrdering = new Vector();      Vector values = new Vector();      X509NameTokenizer xt = new X509NameTokenizer(dn);      while (xt.hasMoreTokens()) {        // This is a pair (CN=xx)        String pair = xt.nextToken();        int ix = pair.indexOf("=");        if (ix != -1) {          String key = pair.substring(0, ix).toLowerCase();          String val = pair.substring(ix + 1);          // -- First search the OID by name in declared OID's          DERObjectIdentifier oid = DnComponents.getOid(key);          try {              // -- If isn't declared, we try to create it              if (oid == null) {                oid = new DERObjectIdentifier(key);              }              defaultOrdering.add(oid);              values.add(val);                        } catch (IllegalArgumentException e) {              // If it is not an OID we will ignore it              log.warn("Unknown DN component ignored and silently dropped: " + key);          }        } else {            log.warn("Huh, what's this? DN: " + dn+" PAIR: "+pair);        }      }      X509Name x509Name = new X509Name(defaultOrdering, values, converter);      //-- Reorder fields      X509Name orderedX509Name = getOrderedX509Name(x509Name, getDefaultX509FieldOrder(), converter);      //log.debug("<stringToBcX509Name");      return orderedX509Name;    } // stringToBcX509Name        /**     * Every DN-string should look the same. Creates a name string ordered and looking like we want     * it...     *     * @param dn String containing DN     *     * @return String containing DN, or null if input is null     */    public static String stringToBCDNString(String dn) {        //log.debug(">stringToBcDNString: "+dn);    	if (isDNReversed(dn)) {    		dn = reverseDN(dn);    	}        String ret = null;        X509Name name = stringToBcX509Name(dn);        if (name != null) {            ret = name.toString();        }        //log.debug("<stringToBcDNString: "+ret);        return ret;    }    /**     * Convenience method for getting an email addresses from a DN. Uses {@link     * getPartsFromDN(String,String)} internally, and searches for {@link EMAIL}, {@link EMAIL1},     * {@link EMAIL2}, {@link EMAIL3} and returns the first one found.     *     * @param dn the DN     *	 * @return ArrayList containing email or empty list if email is not present     * @return the found email address, or <code>null</code> if none is found     */    public static ArrayList getEmailFromDN(String dn) {        log.debug(">getEmailFromDN(" + dn + ")");        ArrayList ret = new ArrayList();        for (int i = 0; i < EMAILIDS.length ; i++) {            ArrayList emails = getPartsFromDN(dn, EMAILIDS[i]);            if (emails.size() > 0) {            	ret.addAll(emails);            }                    }

⌨️ 快捷键说明

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