本文介紹了如何從 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!