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

Sur*_*tta 7 java security encryption bouncycastle x509certificate

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

    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();
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码生成带有私钥和公钥的证书.

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

从这里得到了一些意见,似乎这不是我案例的必要答案.

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

Dav*_*e B 1

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

        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 /sf/ask/506123131/
Run Code Online (Sandbox Code Playgroud)