How to read EC Private key in java which is in .pe

2019-07-10 03:46发布

问题:

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

回答1:

From an EC PRIVATE KEY as requested (ex key.pem), I succeeded to import it in a java.security.KeyStore

  1. transform private key from PEM => PKCS#8 DER
    openssl pkcs8 -in key.pem -inform PEM -topk8 -nocrypt -out key-pkcs8.der -outform DER
  1. 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});
}


标签: java security