57

I'm wondering if it's possible to recover a RSA public key that I have converted to byte array previously.

byte[] keyBytes = publicKey.getEncoded();

Thanks for the help.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
kiewic
  • 15,852
  • 13
  • 78
  • 101

3 Answers3

118
PublicKey publicKey = 
    KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

For more info see this tutorial

madth3
  • 7,275
  • 12
  • 50
  • 74
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
45

For others who want to get private key instead of public key from byte array:

PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
Marko Kotar
  • 449
  • 4
  • 5
-1

Great answer. Thanks for the link. Just for complete, I found this Converted secret key into bytes, how to convert it back to secrect key?

SecretKey key2 = new SecretKeySpec(data, 0, data.length, "DES");

and just worked very well.

Community
  • 1
  • 1
Adrien
  • 365
  • 3
  • 9