Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java
22,728
Solution 1
Use Bouncy Castle's SubjectPublicKeyInfo
, like this:
byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
Solution 2
Without BouncyCastle:
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));
Author by
Ashish Kumar Shah
Likes reading manga and watching sitcoms. Writes Code for a living, and thinks that he is good at it.
Updated on August 04, 2021Comments
-
Ashish Kumar Shah almost 3 years
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?
-
Ashish Kumar Shah over 11 yearsThis 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.
-
Ashish Kumar Shah over 11 yearsThanks a bunch! Your approach worked. I am posting the exact snippet i used.
-
ruckc over 8 yearsThe
getPublicKey()
is a deprecated function now. -
Manuel over 6 years
new SubjectPublicKeyInfo(..)
is deprecated as well: UseSubjectPublicKeyInfo.getInstance(...)
. And instead ofgetPublicKey()
useparsePublicKey()
. -
Maarten Bodewes almost 3 yearsThe 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).
-
martijno almost 3 yearsHey Maarten. @AshishKumarShah's comment was probably about my answer before I edited (back in 2012 :) ).