如何使用新的Bouncy Castle库从PKCS10CertificationRequest获取公钥?

时间:2012-06-14 07:56:31

标签: java cryptography bouncycastle

在新版本的Bouncy Castle库中,PKCS10CertificationRequest发生了变化。在以前的版本中,可以使用PublicKey方法从此类请求中获取getPublicKey()(请参阅old doc)。

现在这种方法消失了。如何通过此类请求获取PublicKey? 有getSubjectPublicKeyInfo().parsePublicKey(),但它会返回ASN1Primitive

我从SPKAC NetscapeCertRequest看到,我仍然可以通过调用getPublicKey()直接阅读PublicKey。

4 个答案:

答案 0 :(得分:11)

主提供程序包中有一个名为PublicKeyFactory的实用程序类。方法createKey返回AsymmetricKeyParameter,您可以将其转换为适合的任何类型的公钥,例如。

SubjectPublicKeyInfo pkInfo = pkcs10CertReq.getSubjectPublicKeyInfo();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);

编辑1:

此外,要创建java.security.PublicKey,还需要执行更多步骤:

RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey rsaPub = kf.generatePublic(rsaSpec);

答案 1 :(得分:5)

我正在研究同样的问题,这也会起作用(我们不需要指定算法):

SubjectPublicKeyInfo pkInfo = pkcs10CertReq.getSubjectPublicKeyInfo();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PublicKey pubKey = converter.getPublicKey(pkInfo);

请参阅org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter

答案 2 :(得分:1)

如何使用JcaPKCS10CertificationRequest?

JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(pkcs10CertReq);
PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

答案 3 :(得分:0)

PKCS10CertificationRequest csr =...;    
PublicKey pk = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(csr.getSubjectPublicKeyInfo().toASN1Primitive().getEncoded()));

RFC 2986 - PKCS #10: Certification Request Syntax

  

CertificationRequestInfo :: = SEQUENCE {
          版本INTEGER {v1(0)}(v1,...),
          主题名称,
          subjectPKInfo SubjectPublicKeyInfo {{PKInfoAlgorithms}},
          attributes [0] Attributes {{CRIAttributes}}
     }

     

SubjectPublicKeyInfo {ALGORITHM:IOSet} :: = SEQUENCE {
          算法AlgorithmIdentifier {{IOSet}},
          subjectPublicKey BIT STRING
     }

然后,您可以看到java.security.spec.X509EncodedKeySpec的文档

  

SubjectPublicKeyInfo :: = SEQUENCE {
     算法AlgorithmIdentifier,
     subjectPublicKey BIT STRING}

因此您将知道此公钥的编码是X.509。然后将其更改为X509EncodedKeySpec并通过keyFactory生成公钥