我使用以下命令从PKCS12文件创建了私钥:
openssl pkcs12 -in test.p12 -nocerts -out privateKey.pem
如何从此privateKey.pem
文件创建PrivateKey对象?
我尝试使用此代码使用PKCS12文件:
KeyStore pfx = KeyStore.getInstance("pkcs12");
pfx.load(new FileInputStream(P12), "123456".toCharArray());
final Enumeration<String> aliases = pfx.aliases(); //this is empty
pfx.aliases()
- 是空的,我使用keytool验证它真的是空的,没有条目。
keytool -v -list -storetype pkcs12 -keystore test.p12
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 0 entries
我的问题是我如何使用这样的代码创建PrivateKey:
public static RSAPrivateKey getPrivateKey(File privateKeyFile) throws IOException {
byte[] keyBytes = new byte[(int) privateKeyFile.length()];
FileInputStream fis = new FileInputStream(privateKeyFile);
fis.read(keyBytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);// it works only with PKCS8
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
return privKey;
}
这段代码的问题只适用于PKCS8,我需要这样的PKCS12。
我知道的唯一方法是有点低级,但它的工作原理:
public PrivateKey getPrivateKey(File file) throws IOException, GeneralSecurityException {
try (FileInputStream fileStream = new FileInputStream(file);
DataInputStream dataStream = new DataInputStream(fileStream)) {
byte[] keyBytes = new byte[(int) file.length()];
dataStream.readFully(keyBytes);
String temp = new String(keyBytes);
String header = temp.replace("-----BEGIN PRIVATE KEY-----\n", "");
header = header.replace("-----END PRIVATE KEY-----", "");
byte[] decoded = new Base64().decode(header);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
此代码假定,所需密钥是RSA密钥。
您可以尝试使用KeyStore Explorer(https://keystore-explorer.org/),我们使用它来代替Java Keytool(因为我发现它难以使用)。