如何将String转换为PublicKey?

编程入门 行业动态 更新时间:2024-10-16 20:24:22
本文介绍了如何将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?

本文发布于:2023-06-08 21:31:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   String   PublicKey

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!