创建密钥对证书并使用BouncyCastle与外部CA签名

时间:2014-01-27 07:43:20

标签: java security encryption x509certificate bouncycastle

这是我到目前为止为用户生成证书

    try {
        Security.addProvider(new BouncyCastleProvider()); // adding provider
                                                            // to
        String pathtoSave = "D://sureshtest.cer";

        KeyPair keyPair = generateKeypair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        X509Certificate trustCert = createCertificate(null, "CN=CompanyName",
                "CN=Owner", publicKey, privateKey);
        java.security.cert.Certificate[] outChain = { trustCert, };
        trustCert.checkValidity();
        KeyStore outStore = KeyStore.getInstance("PKCS12");
        outStore.load(null, null);
        outStore.setKeyEntry("my own certificate", privateKey,
                "admin123".toCharArray(), outChain);
        OutputStream outputStream = new FileOutputStream(pathtoSave);
        outStore.store(outputStream, "admin123".toCharArray());
        outputStream.flush();
        outputStream.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

上述代码使用私钥和公钥生成证书。

现在我想用证书颁发机构(CA)签发的签名证书签署该证书。之后,我会将该证书授予用户。

我收到了一些输入from here,似乎这不是我个案的必要答案。

无需完整实施,只需一个有效的程序或一些提示将有很大帮助。

1 个答案:

答案 0 :(得分:1)

您需要生成CSR,以便可以调用使用BC API的Sign CSR using Bouncy Castle代码。将其添加到上面的代码中:

        final PKCS10 request = new PKCS10(publicKey);
        final String sigAlgName = "SHA1WithRSA"; // change this to SHA1WithDSA if it's a DSA key
        final Signature signature = Signature.getInstance(sigAlgName);
        signature.initSign(privateKey);
        final X500Name subject = new X500Name(trustCert.getSubjectDN().toString());
        final X500Signer signer = new X500Signer(signature, subject);

        // Sign the request and base-64 encode it
        request.encodeAndSign(signer);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintStream writer = new PrintStream(baos);
        request.print(writer);
        // Remove -----BEGIN NEW CERTIFICATE REQUEST----- and -----END NEW CERTIFICATE REQUEST-----
        final String requestBase64 = new String(baos.toByteArray());
        String withoutTags = requestBase64.substring(41);
        withoutTags = withoutTags.substring(0, withoutTags.length() - 39);

        // org.bouncycastle.pkcs.PKCS10CertificationRequestHolder
        final PKCS10CertificationRequest holder = new PKCS10CertificationRequest(Base64.decode(withoutTags));
        // Feed this into https://stackoverflow.com/questions/7230330/sign-csr-using-bouncy-castle