How to convert from String to PublicKey?

大兔子大兔子 提交于 2019-12-03 18:42:15

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28294663/how-to-convert-from-string-to-publickey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!