本文介绍了Java如何使用私钥文件而不是PEM来解密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java和Bouncy Castle 1.52,我可以使用以下代码通过PEM证书加载私钥。我也有一个相同的PKCS8格式的private.key文件。什么是直接使用private.key文件而不是PEM的代码?
Using Java and Bouncy Castle 1.52, I can load the private key through the PEM certificate using the following code. I also have a private.key file of the same in PKCS8 format. What is the code to use the private.key file directly instead of the PEM?
String keyPath = "C:\\RSA7\\privatenopass.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
cipher.init(Cipher.DECRYPT_MODE, kp.getPrivate());
推荐答案
已解决。下面为我工作。
Resolved. The following worked for me.
File mypkfile = new File("C:\\myfolder\\private.key");
byte[] myPK = fullyReadFile(mypkfile);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(myPK);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(privateKeySpec);
cipher.init(Cipher.DECRYPT_MODE, privKey);
fullReadFIle方法:
The fullyReadFIle method:
public static byte[] fullyReadFile(File file) throws IOException
{
DataInputStream dis = new DataInputStream(new FileInputStream(file));
byte[] bytesOfFile = new byte[(int) file.length()];
dis.readFully(bytesOfFile);
dis.close();
return bytesOfFile;
}
这篇关于Java如何使用私钥文件而不是PEM来解密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!