📄 certtools.java
字号:
* Tries to determine if a DN is in reversed form. It does this by taking the last attribute * and the first attribute. If the last attribute comes before the first in the dNObjects array * the DN is assumed to be in reversed order. * * @param dn String containing DN to be checked, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz". * * @return true if the DN is believed to be in reversed order, false otherwise */ public static boolean isDNReversed(String dn) { //log.debug(">isDNReversed: dn: " + dn); boolean ret = false; if (dn != null) { String first = null; String last = null; X509NameTokenizer xt = new X509NameTokenizer(dn); if (xt.hasMoreTokens()) { first = xt.nextToken(); } while (xt.hasMoreTokens()) { last = xt.nextToken(); } if ( (first != null) && (last != null) ) { first = first.substring(0,first.indexOf('=')); last = last.substring(0,last.indexOf('=')); int firsti = 0, lasti = 0; for (int i = 0; i < dNObjects.length; i++) { if (first.toLowerCase().equals(dNObjectsForward[i])) { firsti = i; } if (last.toLowerCase().equals(dNObjectsForward[i])) { lasti = i; } } if (lasti < firsti) { ret = true; } } } //log.debug("<isDNReversed: " + ret); return ret; } //isDNReversed /** * Gets a specified part of a DN. Specifically the first occurrence it the DN contains several * instances of a part (i.e. cn=x, cn=y returns x). * * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz". * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc. * * @return String containing dnpart or null if dnpart is not present */ public static String getPartFromDN(String dn, String dnpart) { log.debug(">getPartFromDN: dn:'" + dn + "', dnpart=" + dnpart); String part = null; if ((dn != null) && (dnpart != null)) { String o; dnpart += "="; // we search for 'CN=' etc. X509NameTokenizer xt = new X509NameTokenizer(dn); while (xt.hasMoreTokens()) { o = xt.nextToken(); //log.debug("checking: "+o.substring(0,dnpart.length())); if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) { part = o.substring(dnpart.length()); break; } } } log.debug("<getpartFromDN: resulting DN part=" + part); return part; } //getPartFromDN /** * Gets a specified parts of a DN. Returns all occurences as an ArrayList, also works if DN contains several * instances of a part (i.e. cn=x, cn=y returns {x, y, null}). * * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz". * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc. * * @return ArrayList containing dnparts or empty list if dnpart is not present */ public static ArrayList getPartsFromDN(String dn, String dnpart) { log.debug(">getPartsFromDN: dn:'" + dn + "', dnpart=" + dnpart); ArrayList parts = new ArrayList(); if ((dn != null) && (dnpart != null)) { String o; dnpart += "="; // we search for 'CN=' etc. X509NameTokenizer xt = new X509NameTokenizer(dn); while (xt.hasMoreTokens()) { o = xt.nextToken(); if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) { parts.add(o.substring(dnpart.length())); } } } log.debug("<getpartsFromDN: resulting DN part=" + parts.toString()); return parts; } //getPartFromDN /** * Gets subject DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate * * @return String containing the subjects DN. */ public static String getSubjectDN(X509Certificate cert) { return getDN(cert, 1); } /** * Gets issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate * * @return String containing the issuers DN. */ public static String getIssuerDN(X509Certificate cert) { return getDN(cert, 2); } /** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate * @param which DOCUMENT ME! * * @return String containing the DN. */ private static String getDN(X509Certificate cert, int which) { //log.debug(">getDN("+which+")"); String dn = null; if (cert == null) { return dn; } try { CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream( cert.getEncoded())); //log.debug("Created certificate of class: " + x509cert.getClass().getName()); if (which == 1) { dn = x509cert.getSubjectDN().toString(); } else { dn = x509cert.getIssuerDN().toString(); } } catch (CertificateException ce) { log.error("CertificateException: ", ce); return null; } //log.debug("<getDN("+which+"):"+dn); return stringToBCDNString(dn); } // getDN /** * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8. * * @param crl X509RL * * @return String containing the DN. */ public static String getIssuerDN(X509CRL crl) { //log.debug(">getIssuerDN(crl)"); String dn = null; try { CertificateFactory cf = CertTools.getCertificateFactory(); X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl.getEncoded())); //log.debug("Created certificate of class: " + x509crl.getClass().getName()); dn = x509crl.getIssuerDN().toString(); } catch (CRLException ce) { log.error("CRLException: ", ce); return null; } //log.debug("<getIssuerDN(crl):"+dn); return stringToBCDNString(dn); } // getIssuerDN public static CertificateFactory getCertificateFactory() { try { return CertificateFactory.getInstance("X.509", "BC"); } catch (NoSuchProviderException nspe) { log.error("NoSuchProvider: ", nspe); } catch (CertificateException ce) { log.error("CertificateException: ", ce); } return null; } public static void installBCProvider() { if (Security.addProvider(new BouncyCastleProvider()) < 0) { // If already installed, remove so we can handle redeploy Security.removeProvider("BC"); if (Security.addProvider(new BouncyCastleProvider()) < 0) { log.error("Cannot even install BC provider again!"); } } } /** * Reads a certificate in PEM-format from a file. The file may contain other things, * the first certificate in the file is read. * * @param certFile the file containing the certificate in PEM-format * @return Ordered Collection of X509Certificate, first certificate first, or empty Collection * @exception IOException if the filen cannot be read. * @exception CertificateException if the filen does not contain a correct certificate. */ public static Collection getCertsFromPEM(String certFile) throws IOException, CertificateException { log.debug(">getCertfromPEM: certFile=" + certFile); InputStream inStrm = new FileInputStream(certFile); Collection certs = getCertsFromPEM(inStrm); log.debug("<getCertfromPEM: certFile=" + certFile); return certs; } /** * Reads a certificate in PEM-format from an InputStream. The stream may contain other things, * the first certificate in the stream is read. * * @param certFile the input stream containing the certificate in PEM-format * @return Ordered Collection of X509Certificate, first certificate first, or empty Collection * @exception IOException if the stream cannot be read. * @exception CertificateException if the stream does not contain a correct certificate. */ public static Collection getCertsFromPEM(InputStream certstream) throws IOException, CertificateException { log.debug(">getCertfromPEM:"); ArrayList ret = new ArrayList(); String beginKey = "-----BEGIN CERTIFICATE-----"; String endKey = "-----END CERTIFICATE-----"; BufferedReader bufRdr = new BufferedReader(new InputStreamReader(certstream)); while (bufRdr.ready()) { ByteArrayOutputStream ostr = new ByteArrayOutputStream(); PrintStream opstr = new PrintStream(ostr); String temp; while ((temp = bufRdr.readLine()) != null && !temp.equals(beginKey)) continue; if (temp == null) throw new IOException("Error in " + certstream.toString() + ", missing " + beginKey + " boundary"); while ((temp = bufRdr.readLine()) != null && !temp.equals(endKey)) opstr.print(temp); if (temp == null) throw new IOException("Error in " + certstream.toString() + ", missing " + endKey + " boundary"); opstr.close(); byte[] certbuf = Base64.decode(ostr.toByteArray()); ostr.close(); // Phweeew, were done, now decode the cert from file back to X509Certificate object CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certbuf)); ret.add(x509cert); } log.debug("<getcertfromPEM:" + ret.size()); return ret; } // getCertsFromPEM /** * Returns a certificate in PEM-format. * * @param cert the certificate to convert to PEM * @return byte array containing PEM certificate * @exception IOException if the stream cannot be read. * @exception CertificateException if the stream does not contain a correct certificate. */ public static byte[] getPEMFromCerts(Collection certs) throws CertificateException { String beginKey = "-----BEGIN CERTIFICATE-----"; String endKey = "-----END CERTIFICATE-----"; ByteArrayOutputStream ostr = new ByteArrayOutputStream(); PrintStream opstr = new PrintStream(ostr); Iterator iter = certs.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate)iter.next(); byte[] certbuf = Base64.encode(cert.getEncoded()); opstr.println("Subject: "+cert.getSubjectDN()); opstr.println("Issuer: "+cert.getIssuerDN()); opstr.println(beginKey); opstr.println(new String(certbuf)); opstr.println(endKey); } opstr.close(); byte[] ret = ostr.toByteArray(); return ret; } /** * Creates X509Certificate from byte[]. * * @param cert byte array containing certificate in DER-format * * @return X509Certificate * * @throws CertificateException if the byte array does not contain a proper certificate. * @throws IOException if the byte array cannot be read. */ public static X509Certificate getCertfromByteArray(byte[] cert) throws CertificateException { log.debug(">getCertfromByteArray:"); CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert)); log.debug("<getCertfromByteArray:"); return x509cert; } // getCertfromByteArray /** * Creates X509CRL from byte[]. * * @param crl byte array containing CRL in DER-format * * @return X509CRL * * @throws IOException if the byte array can not be read. * @throws CertificateException if the byte arrayen does not contani a correct CRL. * @throws CRLException if the byte arrayen does not contani a correct CRL. */ public static X509CRL getCRLfromByteArray(byte[] crl) throws IOException, CRLException { log.debug(">getCRLfromByteArray:"); if (crl == null) { throw new IOException("Cannot read byte[] that is 'null'!"); } CertificateFactory cf = CertTools.getCertificateFactory(); X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl)); log.debug("<getCRLfromByteArray:"); return x509crl;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -