Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java
Asked Answered
T

3

13

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?

Tellurize answered 27/12, 2012 at 9:40 Comment(0)
K
20

Use Bouncy Castle's SubjectPublicKeyInfo, like this:

byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
        ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
Keeter answered 27/12, 2012 at 9:53 Comment(4)
This doesn't serve the pourpose. here we have just casted the public key into a RSAPublicKey object, but when i say RSAPublicKey.getEncoded(), i still get the key in x.509 format and not RSA format.Tellurize
Thanks a bunch! Your approach worked. I am posting the exact snippet i used.Tellurize
The above comment from @AshishKumarShah seems incorrect; I do get a DER encoded key of course, but it does seem to be a PKCS#1 formatted key (ps Hi Martijn, hope everything is OK).Peroneus
Hey Maarten. @AshishKumarShah's comment was probably about my answer before I edited (back in 2012 :) ).Keeter
E
5

Without BouncyCastle:

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));                
Everara answered 28/2, 2013 at 14:5 Comment(0)
T
0

The following snippet of code worked for me, had to use BouncyCastle though.

byte[] keyBytes = key.getEncoded(); // X.509 for public key
SubjectPublicKeyInfo subPkInfo = new SubjectPublicKeyInfo((ASN1Sequence)ASN1Object.fromByteArray(keyBytes));
byte[] rsaformat = subPkInfo.getPublicKey().getDEREncoded();
Tellurize answered 28/12, 2012 at 10:23 Comment(2)
The getPublicKey() is a deprecated function now.Deragon
new SubjectPublicKeyInfo(..) is deprecated as well: Use SubjectPublicKeyInfo.getInstance(...). And instead of getPublicKey() use parsePublicKey().Melaniemelanin

© 2022 - 2024 — McMap. All rights reserved.