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));                
Share:
22,728
Ashish Kumar Shah
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, 2021

Comments

  • Ashish Kumar Shah
    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
    Ashish Kumar Shah over 11 years
    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.
  • Ashish Kumar Shah
    Ashish Kumar Shah over 11 years
    Thanks a bunch! Your approach worked. I am posting the exact snippet i used.
  • ruckc
    ruckc over 8 years
    The getPublicKey() is a deprecated function now.
  • Manuel
    Manuel over 6 years
    new SubjectPublicKeyInfo(..) is deprecated as well: Use SubjectPublicKeyInfo.getInstance(...). And instead of getPublicKey() use parsePublicKey().
  • Maarten Bodewes
    Maarten Bodewes almost 3 years
    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).
  • martijno
    martijno almost 3 years
    Hey Maarten. @AshishKumarShah's comment was probably about my answer before I edited (back in 2012 :) ).