作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我使用以下命令从 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
我的问题是如何使用如下代码创建私钥:
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);
}
}
此代码假定所需的 key 是 RSA key 。
关于java - 从 PKCS12 创建私钥对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644286/
我是一名优秀的程序员,十分优秀!