39点博客

39点博客
像小蜜蜂一样生活

【国密SM2算法】JAVA创建pkcs10格式的csr证书请求文件

 

 代码:

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

image.png

image.png







原创类文章未经允许请勿转载:39点博客 » 【国密SM2算法】JAVA创建pkcs10格式的csr证书请求文件

分享到: +More

评论 6

换个身份

取消评论
  1. #1
    访客
    公钥参数是不是不对啊?
    访客 5年前 (2020-04-14)回复
  2. #2
    访客
    怎么才能生成双证书的CSR啊?
    访客 5年前 (2020-06-01)回复
    • SunShine
      双证书需要用硬件密码机生成
      SunShine 4年前 (2020-07-22)回复
  3. #3
    访客
    提醒一下,这样生成的密钥对是ECDSA,签发后的证书也是ECDSA证书,
    访客 4年前 (2020-07-22)回复