如何从 String 转换为 PublicKey?

How to convert from String to PublicKey?(如何从 String 转换为 PublicKey?)
本文介绍了如何从 String 转换为 PublicKey?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我使用以下代码将公钥和私钥转换为字符串

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);

我收到无法从 byte[] 转换为公钥的错误.所以我就这样尝试了

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");

这会导致如下错误

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.

推荐答案

我认为你不能将 SecretKeySpec 与 RSA 一起使用.

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

应该这样做:

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

并解码私用PKCS8EncodedKeySpec

这篇关于如何从 String 转换为 PublicKey?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)