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

📄 certtools.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            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 DERInputStream(                            new ByteArrayInputStream(pubKey.getEncoded())).readObject());                SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(                            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 DERInputStream(new ByteArrayInputStream(extvalue)).readObject());        AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier((ASN1Sequence) new DERInputStream(                    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 DERInputStream(new ByteArrayInputStream(extvalue)).readObject());        SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(new DERInputStream(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 DERInputStream(new ByteArrayInputStream(extvalue)).readObject());        ASN1Sequence seq = (ASN1Sequence)new DERInputStream(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()) {                List listitem = (List) i.next();                Integer no = (Integer) listitem.get(0);                if (no.intValue() == 0) {                    byte[] altName = (byte[]) listitem.get(1);                    DERObject oct = (DERObject) (new DERInputStream(new ByteArrayInputStream(altName)).readObject());                    ASN1Sequence seq = ASN1Sequence.getInstance(oct);                    ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);                    DERUTF8String str = DERUTF8String.getInstance(obj.getObject());                    return str.getString();                }            }        }        return null;    } // getUPNAltName    /**     * Return the CRL distribution point URL form a certificate.     */    public static URL getCrlDistributionPoint(X509Certificate certificate)      throws CertificateParsingException {        try {            DERObject obj = getExtensionValue(certificate, X509Extensions                                              .CRLDistributionPoints.getId());            if (obj == null) {                return null;            }            ASN1Sequence distributionPoints = (ASN1Sequence) obj;            for (int i = 0; i < distributionPoints.size(); i++) {                ASN1Sequence distrPoint = (ASN1Sequence) distributionPoints.getObjectAt(i);                for (int j = 0; j < distrPoint.size(); j++) {                    ASN1TaggedObject tagged = (ASN1TaggedObject) distrPoint.getObjectAt(j);                    if (tagged.getTagNo() == 0) {                        String url                          = getStringFromGeneralNames(tagged.getObject());                        if (url != null) {                            return new URL(url);                        }                    }                }            }        }        catch (Exception e) {            e.printStackTrace();            throw new CertificateParsingException(e.toString());        }        return null;    }    /**     * Return an Extension DERObject from a certificate     */    private static DERObject getExtensionValue(X509Certificate cert, String oid)      throws IOException {        byte[] bytes = cert.getExtensionValue(oid);        if (bytes == null) {            return null;        }        ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));        ASN1OctetString octs = (ASN1OctetString) aIn.readObject();        aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));        return aIn.readObject();    } //getExtensionValue    private static String getStringFromGeneralNames(DERObject names) {         ASN1Sequence namesSequence = ASN1Sequence.getInstance((ASN1TaggedObject)names, false);         if (namesSequence.size() == 0) {             return null;         }         DERTaggedObject taggedObject           = (DERTaggedObject)namesSequence.getObjectAt(0);         return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets());     } //getStringFromGeneralNames        /**     * Generate SHA1 fingerprint in string representation.     *     * @param ba Byte array containing DER encoded X509Certificate.     *     * @return String containing hex format of SHA1 fingerprint.     */    public static String getCertFingerprintAsString(byte[] ba) {        try {            X509Certificate cert = getCertfromByteArray(ba);            byte[] res = generateSHA1Fingerprint(cert.getEncoded());            return Hex.encode(res);        } catch (CertificateEncodingException cee) {            log.error("Error encoding X509 certificate.", cee);        } catch (CertificateException cee) {            log.error("Error decoding X509 certificate.", cee);        } catch (IOException ioe) {            log.error("Error reading byte array for X509 certificate.", ioe);        }        return null;    }    /**     * Generate SHA1 fingerprint of certificate in string representation.     *     * @param cert X509Certificate.     *     * @return String containing hex format of SHA1 fingerprint.     */    public static String getFingerprintAsString(X509Certificate cert) {        try {            byte[] res = generateSHA1Fingerprint(cert.getEncoded());            return Hex.encode(res);        } catch (CertificateEncodingException cee) {            log.error("Error encoding X509 certificate.", cee);        }        return null;    }    /**     * Generate SHA1 fingerprint of CRL in string representation.     *     * @param crl X509CRL.     *     * @return String containing hex format of SHA1 fingerprint.     */    public static String getFingerprintAsString(X509CRL crl) {        try {            byte[] res = generateSHA1Fingerprint(crl.getEncoded());            return Hex.encode(res);        } catch (CRLException ce) {            log.error("Error encoding X509 CRL.", ce);        }        return null;    }    /**     * Generate a SHA1 fingerprint from a byte array containing a X.509 certificate     *     * @param ba Byte array containing DER encoded X509Certificate.     *     * @return Byte array containing SHA1 hash of DER encoded certificate.     */    public static byte[] generateSHA1Fingerprint(byte[] ba) {        try {            MessageDigest md = MessageDigest.getInstance("SHA1");            return md.digest(ba);        } catch (NoSuchAlgorithmException nsae) {            log.error("SHA1 algorithm not supported", nsae);        }        return null;    } // generateSHA1Fingerprint    /**     * Generate a MD5 fingerprint from a byte array containing a X.509 certificate     *     * @param ba Byte array containing DER encoded X509Certificate.     *     * @return Byte array containing MD5 hash of DER encoded certificate.     */    public static byte[] generateMD5Fingerprint(byte[] ba) {        try {            MessageDigest md = MessageDigest.getInstance("MD5");            return md.digest(ba);        } catch (NoSuchAlgorithmException nsae) {            log.error("MD5 algorithm not supported", nsae);        }        return null;    } // generateMD5Fingerprint    } // CertTools

⌨️ 快捷键说明

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