Java how to use private key file instead of PEM for decryption?

Using Java and Bouncy Castle 1.52, I can download the private key through the PEM certificate using the following code. I also have the private.key file of the same in PKCS8 format. What is the code to use private.key directly instead of 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());
+4
source share
2 answers

This is simple because Java itself already uses PKCS # 8 encoding to encode RSA private keys.

, PKCS # 8. PKCS # 8 ( , , , ).

Java 7/8 . , .

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);

Bouncy Castle PEM. , , .

0

. .

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:

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;
}
0

All Articles