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

📄 certtools.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
     * @throws NoSuchAlgorithmException DOCUMENT ME!     * @throws SignatureException DOCUMENT ME!     * @throws InvalidKeyException DOCUMENT ME!     * @throws IllegalStateException      * @throws CertificateEncodingException      */    public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage)        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {        // Create self signed certificate        Date firstDate = new Date();        // Set back startdate ten minutes to avoid some problems with wrongly set clocks.        firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));        Date lastDate = new Date();        // validity in days = validity*24*60*60*1000 milliseconds        lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));        X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();                // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this        // bean is created.        byte[] serno = new byte[8];        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");        random.setSeed((new Date().getTime()));        random.nextBytes(serno);        certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());        certgen.setNotBefore(firstDate);        certgen.setNotAfter(lastDate);        certgen.setSignatureAlgorithm(sigAlg);        certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));        certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));        certgen.setPublicKey(pubKey);        // Basic constranits is always critical and MUST be present at-least in CA-certificates.        BasicConstraints bc = new BasicConstraints(isCA);        certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);        // Put critical KeyUsage in CA-certificates        if (isCA == true) {            X509KeyUsage ku = new X509KeyUsage(keyusage);            certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);        }        // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.        try {            if (isCA == true) {                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(                            new ByteArrayInputStream(pubKey.getEncoded())).readObject());                SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(                            new ByteArrayInputStream(pubKey.getEncoded())).readObject());                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);                certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);                certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);            }        } catch (IOException e) { // do nothing        }        // CertificatePolicies extension if supplied policy ID, always non-critical        if (policyId != null) {                PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));                DERSequence seq = new DERSequence(pi);                certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);        }        X509Certificate selfcert = certgen.generate(privKey);        return selfcert;    } //genselfCertForPurpose    /**     * Get the authority key identifier from a certificate extensions     *     * @param cert certificate containing the extension     * @return byte[] containing the authority key identifier     * @throws IOException if extension can not be parsed     */    public static byte[] getAuthorityKeyId(X509Certificate cert)        throws IOException {        byte[] extvalue = cert.getExtensionValue("2.5.29.35");        if (extvalue == null) {            return null;        }        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());        AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier((ASN1Sequence) new ASN1InputStream(                    new ByteArrayInputStream(oct.getOctets())).readObject());        return keyId.getKeyIdentifier();    } // getAuthorityKeyId    /**     * Get the subject key identifier from a certificate extensions     *     * @param cert certificate containing the extension     * @return byte[] containing the subject key identifier     * @throws IOException if extension can not be parsed     */    public static byte[] getSubjectKeyId(X509Certificate cert)        throws IOException {        byte[] extvalue = cert.getExtensionValue("2.5.29.14");        if (extvalue == null) {            return null;        }        ASN1OctetString str = ASN1OctetString.getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());        SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());        return keyId.getKeyIdentifier();    }  // getSubjectKeyId    /**     * Get a certificate policy ID from a certificate policies extension     *     * @param cert certificate containing the extension     * @param pos position of the policy id, if several exist, the first is as pos 0     * @return String with the certificate policy OID     * @throws IOException if extension can not be parsed     */    public static String getCertificatePolicyId(X509Certificate cert, int pos)        throws IOException {        byte[] extvalue = cert.getExtensionValue(X509Extensions.CertificatePolicies.getId());        if (extvalue == null) {            return null;        }        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());        ASN1Sequence seq = (ASN1Sequence)new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject();        // Check the size so we don't ArrayIndexOutOfBounds        if (seq.size() < pos+1) {            return null;        }        PolicyInformation pol = new PolicyInformation((ASN1Sequence)seq.getObjectAt(pos));        String id = pol.getPolicyIdentifier().getId();        return id;    } // getCertificatePolicyId    /**     * Gets the Microsoft specific UPN altName.     *     * @param cert certificate containing the extension     * @return String with the UPN name or null if the altName does not exist     */    public static String getUPNAltName(X509Certificate cert) throws IOException, CertificateParsingException {        Collection altNames = cert.getSubjectAlternativeNames();        if (altNames != null) {            Iterator i = altNames.iterator();            while (i.hasNext()) {                ASN1Sequence seq = getAltnameSequence((List)i.next());                String ret = getUPNStringFromSequence(seq);                if (ret != null) {                    return ret;                }            }        }        return null;    } // getUPNAltName    /** Helper method for the above method     */    private static String getUPNStringFromSequence(ASN1Sequence seq) {        if ( seq != null) {                                // First in sequence is the object identifier, that we must check            DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0));            if (id.getId().equals(CertTools.UPN_OBJECTID)) {                ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);                DERUTF8String str = DERUTF8String.getInstance(obj.getObject());                return str.getString();                                    }        }        return null;    }        /**     * Gets the Microsoft specific GUID altName, that is encoded as an octect string.     *     * @param cert certificate containing the extension     * @return String with the hex-encoded GUID byte array or null if the altName does not exist     */    public static String getGuidAltName(X509Certificate cert)        throws IOException, CertificateParsingException {        Collection altNames = cert.getSubjectAlternativeNames();        if (altNames != null) {            Iterator i = altNames.iterator();            while (i.hasNext()) {                ASN1Sequence seq = getAltnameSequence((List)i.next());                if ( seq != null) {                                        // First in sequence is the object identifier, that we must check                    DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0));                    if (id.getId().equals(CertTools.GUID_OBJECTID)) {                        ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);                        ASN1OctetString str = ASN1OctetString.getInstance(obj.getObject());                        return new String(Hex.encode(str.getOctets()));                                            }                }            }        }        return null;    } // getGuidAltName    /** Helper for the above methods      */    private static ASN1Sequence getAltnameSequence(List listitem) throws IOException {        Integer no = (Integer) listitem.get(0);        if (no.intValue() == 0) {            byte[] altName = (byte[]) listitem.get(1);            return getAltnameSequence(altName);        }        return null;    }    private static ASN1Sequence getAltnameSequence(byte[] value) throws IOException {        DERObject oct = (new ASN1InputStream(new ByteArrayInputStream(value)).readObject());        ASN1Sequence seq = ASN1Sequence.getInstance(oct);        return seq;    }    	/**	 * SubjectAltName ::= GeneralNames	 *	 * GeneralNames :: = SEQUENCE SIZE (1..MAX) OF GeneralName	 *	 * GeneralName ::= CHOICE {	 * otherName                       [0]     OtherName,	 * rfc822Name                      [1]     IA5String,	 * dNSName                         [2]     IA5String,	 * x400Address                     [3]     ORAddress,	 * directoryName                   [4]     Name,	 * ediPartyName                    [5]     EDIPartyName,	 * uniformResourceIdentifier       [6]     IA5String,	 * iPAddress                       [7]     OCTET STRING,	 * registeredID                    [8]     OBJECT IDENTIFIER}	 * 	 * SubjectAltName is of form \"rfc822Name=<email>,	 * dNSName=<host name>, uniformResourceIdentifier=<http://host.com/>,	 * iPAddress=<address>, guid=<globally unique id>, directoryName=<CN=testDirName|dir|name>     *      * Supported altNames are upn, rfc822Name, uniformResourceIdentifier, dNSName, iPAddress, directoryName	 *	 * @author Marco Ferrante, (c) 2005 CSITA - University of Genoa (Italy)     * @author Tomas Gustavsson	 * @param certificate containing alt names	 * @return String containing altNames of form "rfc822Name=email, dNSName=hostname, uniformResourceIdentifier=uri, iPAddress=ip, upn=upn, directoryName=CN=testDirName|dir|name" or null if no altNames exist. Values in returned String is from CertTools constants. AltNames not supported are simply not shown in the resulting string.  	 * @throws java.lang.Exception	 */	public static String getSubjectAlternativeName(X509Certificate certificate) throws Exception {		log.debug("Search for SubjectAltName");		if (certificate.getSubjectAlternativeNames() == null)			return null;				java.util.Collection altNames = certificate.getSubjectAlternativeNames();        if (altNames == null) {            return null;        }        Iterator iter = altNames.iterator();        String result = "";        String append = "";        while (iter.hasNext()) {            java.util.List item = (java.util.List)iter.next();            Integer type = (Integer)item.get(0);            Object value = item.get(1);            if (!StringUtils.isEmpty(result)) {                // Result already contains one altname, so we have to add comma if there are more altNames                append = ", ";            }            switch (type.intValue()) {                case 0: ASN1Sequence seq = getAltnameSequence(item);                    String upn = getUPNStringFromSequence(seq);                    // OtherName can be something else besides UPN                    if (upn != null) {                        result += append + CertTools.UPN+"="+upn;                                            }                    break;                case 1: result += append + CertTools.EMAIL+"=" + (String)value;                    break;                case 2: result += append + CertTools.DNS+"=" + (String)value;                    break;                case 3: // SubjectAltName of type x400Address not supported                    break;                case 4: result += append + CertTools.DIRECTORYNAME+"=" + (String)value;                    break;                case 5: // SubjectAltName of type ediPartyName not supported                    break;                case 6: result += append + CertTools.URI+"=" + (String)value;                    break;                case 7: result += append + CertTools.IPADDR+"=" + (String)value;                    break;                default: // SubjectAltName of unknown type                    break;            }        }        if (StringUtils.isEmpty(result)) {            return null;        }        return result;            	}    /**     * From an altName string as defined in getSubjectAlternativeName      * @param altName     * @return ASN.1 GeneralNames     * @see #getSubjectAlternativeName     */    public static GeneralNames getGeneralNamesFromAltName(String altName) {    	log.debug(">getGeneralNamesFromAltName: "+altName);    	        ASN1EncodableVector vec = new ASN1EncodableVector();        ArrayList emails = CertTools.getEmailFromDN(altName);        if (!emails.isEmpty()) {

⌨️ 快捷键说明

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