This question already has an answer here:
Given this .pem
file (generated with openssl and encrypted with a password):
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,AC009672952033EB
2wegzxf3MtncXS1CY3c.....
....
....
-----END RSA PRIVATE KEY-----
How do I get a PrivateKey
object in Java? I wrote the following code but I cannot find the right way to get a KeySpec
:
PrivateKey readFromPem(File keyFile, String password){
PemReader r = new PemReader(new InputStreamReader(new FileInputStream(keyFile)));
PemObject pemObject = r.readPemObject();
byte[] encodedKey = pemObject.getContent();
KeySpec keySpec = ???? // how to get this?
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
return key;
}
I guess I should build a RSAPrivateKeySpec
, but I don't know how. I tried the method from this answer and this other answer, but they both result in errors when parsing the byte array.
I'm using BouncyCastle 1.57 (bcprov-jdk15on, bcmail-jdk15on and bcpkix-jdk15on) and Java 7.
You can read the private key using the
JcaPEMKeyConverter
class. The code below works for keys with and without a password:The
privateKey
's class will bejava.security.spec.RSAPrivateCrtKeySpec
(which extendsRSAPrivateKeySpec
).Use Bouncy Castle's bcpkix dependency which knows how to handle OpenSSL keys.
and try it like this: