当前位置:和仁网 >其它 > 正文

java中怎么读取.pem格式文件中的 PrivateKey-CSDN论坛

2021-01-22 0

以下命令来生成密钥对。

$openssl genrsa -out mykey.pem 2048

$openssl pkcs8 -topk8 -inform PEM -outform PEM -in mykey.pem
-out private_key.pem -nocrypt

这个命令得到的公共密钥。
$ openssl rsa -in mykey.pem -pubout -outform DER -out public_key.der

我写了法读取私钥和公钥

分别。public PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
File f = new File(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);
String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----n", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
//System.out.println("Private keyn"+privKeyPEM);

Base64 b64 = new Base64();
byte [] decoded = b64.decode(privKeyPEM);

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePrivate(spec);
}

public PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
File f = new File(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);
String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----n", "");
publicKeyPEM = privKeyPEM.replace("-----END PUBLIC KEY-----", "");

Base64 b64 = new Base64();
byte [] decoded = b64.decode(publicKeyPEM);

X509EncodedKeySpec spec =
new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePublic(spec);
}
本周热门
本月热门