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

📄 certtools.java

📁 JAVA做的J2EE下CA认证系统 基于EJB开发
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
    } // getCRLfromByteArray    /**     * Checks if a certificate is self signed by verifying if subject and issuer are the same.     *     * @param cert the certificate that skall be checked.     *     * @return boolean true if the certificate has the same issuer and subject, false otherwise.     */    public static boolean isSelfSigned(X509Certificate cert) {        log.debug(">isSelfSigned: cert: " + CertTools.getIssuerDN(cert) + "\n" +            CertTools.getSubjectDN(cert));        boolean ret = CertTools.getSubjectDN(cert).equals(CertTools.getIssuerDN(cert));        log.debug("<isSelfSigned:" + ret);        return ret;    } // isSelfSigned    /**     * DOCUMENT ME!     *     * @param dn subject and issuer DN     * @param validity in days     * @param policyId policy string ('2.5.29.32.0') or null     * @param privKey private key     * @param pubKey public key     * @param isCA boolean true or false     *     * @return X509Certificate, self signed     *     * @throws NoSuchAlgorithmException DOCUMENT ME!     * @throws SignatureException DOCUMENT ME!     * @throws InvalidKeyException DOCUMENT ME!     */    public static X509Certificate genSelfCert(String dn, long validity, String policyId,        PrivateKey privKey, PublicKey pubKey, boolean isCA)        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {        // Create self signed certificate        String sigAlg = "SHA1WithRSA";        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) {            int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;            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.generateX509Certificate(privKey);        return selfcert;    } //genselfCert    /**     * 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     */    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     */    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 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);            DERObject oct = (new ASN1InputStream(new ByteArrayInputStream(altName)).readObject());            ASN1Sequence seq = ASN1Sequence.getInstance(oct);            return seq;        }        return null;    }        /**     * 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>     *      * Supported altNames are upn, rfc822Name, uniformResourceIdentifier, dNSName, iPAddress,      *     * @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" 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: // SubjectAltName of type directoryName not supported                    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;                }	/**	 * Check the certificate with CA certificate.	 *	 * @param certificate cert to verify	 * @param caCertPath collection of X509Certificate	 * @return true if verified OK, false if not	 */	public static boolean verify(X509Certificate certificate, Collection caCertPath) throws Exception {		try {

⌨️ 快捷键说明

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