本文介紹了如何從 String 轉(zhuǎn)換為 PublicKey?的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我使用以下代碼將公鑰和私鑰轉(zhuǎn)換為字符串
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());
現(xiàn)在我正在嘗試將其轉(zhuǎn)換回公共廣告私鑰
Now I'm trying to convert it back to public ad private key
PublicKey publicDecoded = Base64.decodeBase64(publicK);
我收到無法從 byte[] 轉(zhuǎn)換為公鑰的錯(cuò)誤.所以我就這樣嘗試了
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");
這會(huì)導(dǎo)致如下錯(cuò)誤
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key
看起來我在這里進(jìn)行了錯(cuò)誤的密鑰轉(zhuǎn)換.任何幫助將不勝感激.
Looks like I'm doing wrong key conversion here. Any help would be appreciated.
推薦答案
我認(rèn)為你不能將 SecretKeySpec
與 RSA 一起使用.
I don't think you can use the SecretKeySpec
with RSA.
應(yīng)該這樣做:
byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
并解碼私用PKCS8EncodedKeySpec
這篇關(guān)于如何從 String 轉(zhuǎn)換為 PublicKey?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!