I know that there are several other questions about that topic, but none of them have helped me out. I tried the BouncyCastle
lib as well. Could someone please help me here?
The PEM file looks like:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAq2eYtnTsEc/qyqS ...
... zY3WG++SA+amcXiO721hJWNC+uTbZ1bzQ==
-----END RSA PRIVATE KEY-----
I'm using this method
public static PrivateKey getPemPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
File f = new File(PEMFILES_FOLDER+filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
//TODO care about the linefeeds
String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println("Private key: \n"+privKeyPEM);
Base64 b64 = new Base64();
byte [] decoded = b64.decode(privKeyPEM);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(RSA);
return kf.generatePrivate(spec);
}
I am getting this error:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence