Java 如何从字符串转换为公钥?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28294663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:57:16  来源:igfitidea点击:

How to convert from String to PublicKey?

javaencryptioncryptographypublic-key-encryption

提问by The Coder

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

我收到无法从 byte[] 转换为公钥的错误。所以我试过这样

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.

看起来我在这里进行了错误的密钥转换。任何帮助,将不胜感激。

采纳答案by weston

I don't think you can use the SecretKeySpecwith RSA.

我认为您不能将SecretKeySpec与 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

并解码私人使用 PKCS8EncodedKeySpec