[英]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
openssl pkcs8 -in key.pem -inform PEM -topk8 -nocrypt -out key-pkcs8.der -outform DER
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.