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

📄 certtools.java

📁 JAVA做的J2EE下CA认证系统 基于EJB开发
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
			ArrayList certlist = new ArrayList();			// Create CertPath			certlist.add(certificate);			// Add other certs...						CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");			java.security.cert.CertPath cp = cf.generateCertPath(certlist);			// Create TrustAnchor. Since EJBCA use BouncyCastle provider, we assume			// certificate already in correct order			X509Certificate[] cac = (X509Certificate[]) caCertPath.toArray(new X509Certificate[] {});			java.security.cert.TrustAnchor anchor = new java.security.cert.			TrustAnchor(cac[0], null);			// Set the PKIX parameters			java.security.cert.PKIXParameters params = new java.security.cert.PKIXParameters(java.util.Collections.singleton(anchor));			params.setRevocationEnabled(false);			java.security.cert.CertPathValidator cpv = java.security.cert.			CertPathValidator.getInstance("PKIX", "BC");			java.security.cert.PKIXCertPathValidatorResult result =				(java.security.cert.PKIXCertPathValidatorResult) cpv.validate(cp, params);			log.debug("Certificate verify result: " + result.toString());		} catch (java.security.cert.CertPathValidatorException cpve) {			throw new Exception("Invalid certificate or certificate not issued by specified CA: " + cpve.getMessage());		} catch (Exception e) {			throw new Exception("Error checking certificate chain: " + e.getMessage());		}		return true;	}		/**     * 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) {            log.error("Error parsing CrlDistributionPoint", e);            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);        }        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        /** Converts Sun Key usage bits to Bouncy castle key usage kits     *      * @param sku key usage bit fields according to java.security.cert.X509Certificate#getKeyUsage, must be a boolean aray of size 9.     * @return key usage int according to org.bouncycastle.jce.X509KeyUsage#X509KeyUsage.     * @see java.security.cert.X509Certificate#getKeyUsage     * @see org.bouncycastle.jce.X509KeyUsage#X509KeyUsage     */    public static int sunKeyUsageToBC(boolean[] sku) {        int bcku = 0;        if (sku[0] == true)            bcku = bcku | X509KeyUsage.digitalSignature;        if (sku[1] == true)            bcku = bcku | X509KeyUsage.nonRepudiation;        if (sku[2] == true)            bcku = bcku | X509KeyUsage.keyEncipherment;        if (sku[3] == true)            bcku = bcku | X509KeyUsage.dataEncipherment;        if (sku[4] == true)            bcku = bcku | X509KeyUsage.keyAgreement;        if (sku[5] == true)            bcku = bcku | X509KeyUsage.keyCertSign;        if (sku[6] == true)            bcku = bcku | X509KeyUsage.cRLSign;        if (sku[7] == true)            bcku = bcku | X509KeyUsage.encipherOnly;        if (sku[8] == true)            bcku = bcku | X509KeyUsage.decipherOnly;        return bcku;    }        /**     * Method used to insert a CN postfix into DN by extracting the first found CN appending cnpostfix and then replacing the original CN      * with the new one in DN.     *      * If no CN could be found in DN then should the given DN be returned untouched     *      * @param dn the DN to manipulate, cannot be null     * @param cnpostfix the postfix to insert, cannot be null     * @return the new DN     */    public static String insertCNPostfix(String dn, String cnpostfix){      String newdn = null;            if ((dn != null) && (cnpostfix != null)) {          String o;                    X509NameTokenizer xt = new X509NameTokenizer(dn);          boolean alreadyreplaced = false;          while (xt.hasMoreTokens()) {              o = xt.nextToken();                           if (!alreadyreplaced && (o.length() > 3) &&                      o.substring(0, 3).equalsIgnoreCase("cn=")) {                  o += cnpostfix;                       alreadyreplaced = true;              }              if(newdn==null){            	  newdn=o;              }else{	                  newdn += "," + o;              }            }      }       return newdn;    }        /**     * class for breaking up an X500 Name into it's component tokens, ala     * java.util.StringTokenizer. Taken from BouncyCastle, but does NOT     * use or consider escaped characters. Used for reversing DNs without unescaping.     */    private static class BasicX509NameTokenizer    {        private String          oid;        private int             index;        private StringBuffer    buf = new StringBuffer();        public BasicX509NameTokenizer(            String oid)        {            this.oid = oid;            this.index = -1;        }        public boolean hasMoreTokens()        {            return (index != oid.length());        }        public String nextToken()        {            if (index == oid.length())            {                return null;            }            int     end = index + 1;            boolean quoted = false;            boolean escaped = false;            buf.setLength(0);            while (end != oid.length())            {                char    c = oid.charAt(end);                                if (c == '"')                {                    if (!escaped)                    {                        buf.append(c);                        quoted = !quoted;                    }                    else                    {                        buf.append(c);                    }                    escaped = false;                }                else                {                     if (escaped || quoted)                    {                        buf.append(c);                        escaped = false;                    }                    else if (c == '\\')                    {                        buf.append(c);                        escaped = true;                    }                    else if ( (c == ',') && (!escaped) )                    {                        break;                    }                    else                    {                        buf.append(c);                    }                }                end++;            }            index = end;            return buf.toString().trim();        }    }} // CertTools

⌨️ 快捷键说明

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