12

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?

Mark Whitaker
  • 8,465
  • 8
  • 44
  • 68
Ashish Kumar Shah
  • 512
  • 1
  • 9
  • 26

3 Answers3

17

Use Bouncy Castle's SubjectPublicKeyInfo, like this:

byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
        ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
martijno
  • 1,723
  • 1
  • 23
  • 53
  • 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 Dec 27 '12 at 14:14
  • Thanks a bunch! Your approach worked. I am posting the exact snippet i used. – Ashish Kumar Shah Dec 28 '12 at 10:17
  • 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). – Maarten Bodewes Aug 03 '21 at 22:42
  • Hey Maarten. @AshishKumarShah's comment was probably about my answer before I edited (back in 2012 :) ). – martijno Aug 24 '21 at 08:10
5

Without BouncyCastle:

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));                
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();
Ashish Kumar Shah
  • 512
  • 1
  • 9
  • 26
  • The `getPublicKey()` is a deprecated function now. – ruckc Oct 06 '15 at 17:27
  • `new SubjectPublicKeyInfo(..)` is deprecated as well: Use `SubjectPublicKeyInfo.getInstance(...)`. And instead of `getPublicKey()` use `parsePublicKey()`. – Manuel Oct 24 '17 at 05:07