问题
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());
回答1:
That's simple, as Java itself already uses PKCS#8 encoding to encode RSA private keys.
Note that this example only uses the inner encoding of PKCS#8. PKCS#8 keys actually consist of an a layered structure (inner encoding to indicate key type, which is wrapped, and an outer encoding to indicate the wrapping mechanism used).
It also uses some convenience methods from Java 7/8 to read the bytes from file. You can replace this with any code to read all bytes from the file.
Path path = (new File("privatenopass.pkcs8")).toPath();
byte[] pkcs8Data = Files.readAllBytes(path);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(pkcs8Data);
RSAPrivateKey pk = (RSAPrivateKey) kf.generatePrivate(keyspec);
You directly gave the file reader to Bouncy Castle to decode the PEM. In this case however you do have to perform the stream handling yourself.
回答2:
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);
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;
}
来源:https://stackoverflow.com/questions/30326952/java-how-to-use-private-key-file-instead-of-pem-to-decrypt