📄 certtools.java
字号:
* 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)); String dn=x509cert.getSubjectDN().toString(); 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 IOException, 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, CertificateException, 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; } // 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((long) (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) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -