Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the new version of Bouncy Castle library there are changes in PKCS10CertificationRequest. In previous versions it was possible to get PublicKey from such request using getPublicKey() method (see old doc).

Now this method disappered. How can I get PublicKey from with from such request? There is getSubjectPublicKeyInfo().parsePublicKey() but it returns ASN1Primitive.

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

like image 225
Michał Niklas Avatar asked Jun 14 '12 07:06

Michał Niklas


3 Answers

There is a utility class in the main provider package called PublicKeyFactory. The method createKey returns an AsymmetricKeyParameter which you cast to whatever type of public key is appropriate, e.g.

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

EDIT 1:

In addition, to create a java.security.PublicKey a few more steps are needed:

RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey rsaPub = kf.generatePublic(rsaSpec);
like image 66
President James K. Polk Avatar answered Jan 31 '23 03:01

President James K. Polk


I was looking at the same issue, and this will work too (with the advantage that we don't need to specify the algorithm):

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

See org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter

like image 39
lv. Avatar answered Jan 31 '23 03:01

lv.


What about using JcaPKCS10CertificationRequest?

JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(pkcs10CertReq);
PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
like image 45
amareno Avatar answered Jan 31 '23 03:01

amareno