代码:
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator localKeyPairGenerator = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
localKeyPairGenerator.initialize(256);
KeyPair localKeyPair = localKeyPairGenerator.genKeyPair();
X500NameBuilder localX500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
localX500NameBuilder.addRDN(BCStyle.CN, "39dian test");
localX500NameBuilder.addRDN(BCStyle.C, "CN");
localX500NameBuilder.addRDN(BCStyle.O, "39dian blog");
localX500NameBuilder.addRDN(BCStyle.L, "shanghai");
localX500NameBuilder.addRDN(BCStyle.ST, "shanghai");
localX500NameBuilder.addRDN(BCStyle.EmailAddress, "admin@39dian.com");
X500Name localX500Name = localX500NameBuilder.build();
JcaPKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(localX500Name, localKeyPair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SM3WITHSM2");// 签名算法
ContentSigner signer = csBuilder.build(localKeyPair.getPrivate());
PKCS10CertificationRequest csr = p10Builder.build(signer);// PKCS10的请求
System.out.println(Base64.encodeBase64String(csr.getEncoded()));
}
输出:
MIIBPDCB4wIBADCBgDEUMBIGA1UEAwwLMzlkaWFuIHRlc3QxCzAJBgNVBAYTAkNOMRQwEgYDVQQKDAszOWRpYW4gYmxvZzERMA8GA1UEBwwIc2hhbmdoYWkxETAPBgNVBAgMCHNoYW5naGFpMR8wHQYJKoZIhvcNAQkBFhBhZG1pbkAzOWRpYW4uY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAET+QCG5/fwkC9ZyhaMu7Orrp8UKBkTvjFac3hwQ3q/AWh3NrvVKmRi667e6A8vss5dn41+iccdrgD8X+b9F3rP6AAMAoGCCqBHM9VAYN1A0gAMEUCIAryXsg0WngILGG0czwM9kb0al865O2qiVvAmYoRplHrAiEA29guaAuvcOq+XM/4bXHHqVV3nQyc1oK3/phW6EBav1E=
上面输出的是原始串,完整的csr需要加上begin和end certificate request
-----BEGIN CERTIFICATE REQUEST-----
MIIBPDCB4wIBADCBgDEUMBIGA1UEAwwLMzlkaWFuIHRlc3QxCzAJBgNVBAYTAkNOMRQwEgYDVQQKDAszOWRpYW4gYmxvZzERMA8GA1UEBwwIc2hhbmdoYWkxETAPBgNVBAgMCHNoYW5naGFpMR8wHQYJKoZIhvcNAQkBFhBhZG1pbkAzOWRpYW4uY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAET+QCG5/fwkC9ZyhaMu7Orrp8UKBkTvjFac3hwQ3q/AWh3NrvVKmRi667e6A8vss5dn41+iccdrgD8X+b9F3rP6AAMAoGCCqBHM9VAYN1A0gAMEUCIAryXsg0WngILGG0czwM9kb0al865O2qiVvAmYoRplHrAiEA29guaAuvcOq+XM/4bXHHqVV3nQyc1oK3/phW6EBav1E=
-----END CERTIFICATE REQUEST-----
网上找个第三方网址测试下,可以解析出来
测试网址:https://myssl.com/csr_decode.html
原创类文章未经允许请勿转载:39点博客 » 【国密SM2算法】JAVA创建pkcs10格式的csr证书请求文件