問題描述
我正在使用 RSA 算法生成公鑰和私鑰
I am using RSA algorithm to generate public and private key
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
final PrivateKey privateKey=key.getPrivate();
final PublicKey publickey=key.getPublic();
之后,這些密鑰使用 Base64 編碼器進行編碼并將其保存到數據庫中.
after that these keys are encoded using Base64 encoder and save it into database.
如何在java中將此編碼的字符串轉換為私鑰和公鑰類型是解密文件.使用 Base64Decoder 解碼此字符串時,將得到一個字節數組.如何將此字節數組轉換為公鑰或私鑰類型?
How to convert this encoded String to Private and Public Key Type in java is to decrypt file. when decoding this String using Base64Decoder will get a byte array. how to convert this Byte array to public or private key type?
推薦答案
如果你有一個 byte[] 表示 key 上 getEncoded() 的輸出,你可以使用 KeyFactory 將它轉回一個 PublicKey 對象或 PrivateKey對象.
If you have a byte[] representing the output of getEncoded() on a key, you can use KeyFactory to turn that back into a PublicKey object or a PrivateKey object.
byte[] privateKeyBytes;
byte[] publicKeyBytes;
KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
這篇關于如何將 Byte 數組轉換為 PrivateKey 或 PublicKey 類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!