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?
Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java
Asked Answered
Use Bouncy Castle's SubjectPublicKeyInfo
, like this:
byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
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
Without BouncyCastle:
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));
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();
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.