使用 BouncyCastle API 生成 CSR

2022-01-25 00:00:00 certificate security bouncycastle java

我是 Java 安全方面的新手,偶然发现了这个名为 BouncyCastle 的库.但是他们提供的示例和互联网上的示例要求使用

return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(CN=请求的测试证书")、pair.getPublic()、null、pair.getPrivate()

但是当我使用 PKCS10CertificationRequest 时,它似乎已被弃用.所以我开始研究另一种使用 CertificationRequest 类的方法.但我真的很困惑,构造函数不采用相同的参数,而是采用 CertificationRequestInfo 类,我不知道如何填写.

CertificationRequest 请求 = new CertificationRequest(...);

如果有人能帮我弄清楚如何制作 CSR 以便我可以将其发送到服务器进行签名,那就太棒了.

解决方案

对于最新版本的 BouncyCastle,建议使用 org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder 类创建 CSR.p>

您可以使用此代码片段:

KeyPair pair = generateKeyPair();PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=Requested Test Certificate"), pair.getPublic());JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");ContentSigner 签名者 = csBuilder.build(pair.getPrivate());PKCS10CertificationRequest csr = p10Builder.build(signer);

I am new to the security side of Java and stumbled across this library called BouncyCastle. But the examples that they provide and the ones out on the internet ask to use

return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(
    "CN=Requested Test Certificate"), pair.getPublic(), null, pair.getPrivate()

But when I use PKCS10CertificationRequest, it looks like it is deprecated. So I started looking at another method where I use CertificationRequest class. But I am really confused, the constructor does not take the same parameters instead it takes CertificationRequestInfo class which I am not sure how to fill up.

CertificationRequest request = new CertificationRequest(...);

It would be awesome if someone could help me figure out how to make a CSR so that I can send it to the server for getting it signed.

解决方案

With the recent versions of BouncyCastle it is recommended to create the CSR using the org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder class.

You can use this code snipppet:

KeyPair pair = generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
    new X500Principal("CN=Requested Test Certificate"), pair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = csBuilder.build(pair.getPrivate());
PKCS10CertificationRequest csr = p10Builder.build(signer);

相关文章