How to get PublicKey from PKCS10CertificationRequest using the new Bouncy Castle library?

The new version of the Bouncy Castle library has changes to the PKCS10CertificationRequest . In previous versions, you could get PublicKey from this request using the getPublicKey() method (see the old document ).

Now this method has disappeared. How can I get PublicKey with such a request? There is getSubjectPublicKeyInfo().parsePublicKey() , but it returns ASN1Primitive .

I see that from SPKAC NetscapeCertRequest I can still read PublicKey directly by calling getPublicKey() .

+6
source share
4 answers

In the main package of suppliers there is a utility class PublicKeyFactory . The createKey method returns an AsymmetricKeyParameter that you use for any type of public key, for example,

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

EDIT 1:

In addition, to create java.security.PublicKey you need to follow several steps:

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

I considered the same problem, and this will work too (with the advantage that we do not need to specify an algorithm):

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

See org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter

+4
source

How about using JcaPKCS10CertificationRequest?

 JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(pkcs10CertReq); PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey(); 
+1
source
 PKCS10CertificationRequest csr =...; PublicKey pk = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(csr.getSubjectPublicKeyInfo().toASN1Primitive().getEncoded())); 

RFC 2986 - PKCS # 10: Certificate Request Syntax

CertificationRequestInfo :: = SEQUENCE {
INTEGER version {v1 (0)} (v1, ...),
subject Name,
subjectPKInfo SubjectPublicKeyInfo {{PKInfoAlgorithms}},
attributes [0] Attributes {{CRIAttributes}}
}

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

and then you can see the java.security.spec.X509EncodedKeySpec document

SubjectPublicKeyInfo :: = SEQUENCE {
Algorithm Algorithm Identifier,
subjectPublicKey BIT STRING}

so that you know that the encoding of this public key is X.509. and then change it to X509EncodedKeySpec and generate the keyFactory public key

0
source

Source: https://habr.com/ru/post/918066/


All Articles