简体   繁体   English

如何在java中读取.pem文件格式的EC私钥

[英]How to read EC Private key in java which is in .pem file format

How to read EC private key which is in. Pem file using JAVA.如何使用 JAVA 读取 .pem 文件中的 EC 私钥。 While reading I am getting the following exception.在阅读时,我收到以下异常。

Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported: 00, parsed: 01引起:java.security.InvalidKeyException:IOException:版本不匹配:(支持:00,解析:01

Actually my.其实我的。 Pem file contains private key in the following structure. Pem 文件包含以下结构的私钥。

----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根据请求从 EC PRIVATE KEY (ex key.pem),我成功地将它导入 java.security.KeyStore

  1. transform private key from PEM => PKCS#8 DER从 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)加载它(jvm版本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});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM