23

I've used the following code to convert the public and private key to a string

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(2048); KeyPair keyPair = keyPairGen.genKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); String publicK = Base64.encodeBase64String(publicKey.getEncoded()); String privateK = Base64.encodeBase64String(privateKey.getEncoded()); 

Now I'm trying to convert it back to public ad private key

PublicKey publicDecoded = Base64.decodeBase64(publicK); 

I'm getting error of cannot convert from byte[] to public key. So I tried like this

PublicKey publicDecoded = new SecretKeySpec(Base64.decodeBase64(publicK),"RSA"); 

This leads to error like below

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key 

Looks like I'm doing wrong key conversion here. Any help would be appreciated.

3

1 Answer 1

52

I don't think you can use the SecretKeySpec with RSA.

This should do:

byte[] publicBytes = Base64.decodeBase64(publicK); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); 

And to decode the private use PKCS8EncodedKeySpec

Sign up to request clarification or add additional context in comments.

7 Comments

thanks. I forgot about private key. I'll use PKCS8EncodedKeySpec for private key.
Which import does the above Base64 come from?
@Hooli I think it's from org.apache.commons.codec.binary.Base64. also, you could use Base64.getDecoder().decode(publicK) in the java.util if you use Java 1.8
I am trying to do the same thing but am getting java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException ... when it tries to execute the last line .. keyfactory.generatePublic(keySpec)
@HayaRaed ask a new question, you'll get far more attention.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.