How to read EC private key which is in. Pem file using JAVA. While reading I am getting the following exception.
Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported: 00, parsed: 01
Actually my. Pem file contains private key in the following structure.
----BEGIN EC PRIVATE KEY ------
====+====+===
====+====+===
-----END EC PRIVATE KEY-----
From an EC PRIVATE KEY as requested (ex key.pem), I succeeded to import it in a java.security.KeyStore
- transform private key from PEM => PKCS#8 DER
openssl pkcs8 -in key.pem -inform PEM -topk8 -nocrypt -out key-pkcs8.der -outform DER
- load it (jvm version java-1.8.0-openjdk-1.8.0.201.b09-2.fc28.x86_64)
void loadPrivateKey(KeyStore ks, X509Certificate cert){
File privKeyFile = new File("key-pkcs8.der");
// read private key DER file
DataInputStream dis = new DataInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new byte[(int)privKeyFile.length()];
dis.read(privKeyBytes);
dis.close();
KeyFactory kf = KeyFactory.getInstance("EC");
// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
PrivateKey privKey = kf.generatePrivate(privSpec);
ks.setKeyEntry("key-alias", privKey, "password".toCharArray(), new Certificate[] {cert});
}