Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java

The PublicKey.getEncoded(), returns a byte array containing the public key in SubjectPublicKeyInfo (x.509) format, how do i convert it to RSA public key encoding?

like image 459
Ashish Kumar Shah Avatar asked Dec 27 '12 09:12

Ashish Kumar Shah


2 Answers

Use Bouncy Castle's SubjectPublicKeyInfo, like this:

byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
        ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
like image 65
martijno Avatar answered Sep 24 '22 10:09

martijno


Without BouncyCastle:

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));                
like image 27
Michael Webster Avatar answered Sep 25 '22 10:09

Michael Webster