我得到需要转换为 .p12
文件的外部 .pem
文件 - 我在此过程中添加了用户名和密码。 (我需要这样做才能利用第三方 API。)
使用openssl
,命令是...
openssl pkcs12 -export -in xxxx.pem -inkey xxxx.pem -out xxx.p12 -passout pas:newpassword -name "newname"
我可以从终端 session 运行它,它运行得很好。
但是,我需要经常这样做,并且编写了一个 Java 类来处理这个以及更多(我的应用程序主要是 .jsp
,带有 Tomcat 和 Apache)。当我尝试使用 Runtime.exec
从 Java 运行相同的命令时,我遇到了可怕的“无法写入‘随机状态’”错误 (Using OpenSSL what does "unable to write 'random state'" mean?)。
我认为不同之处在于,当我从 Java 运行时,用户不是“root”。
那么,有没有更好的方法使用 Java 库而不是执行命令行程序(即 openssl)将 pem 转换为 .p12?
否则,我想我需要在我的服务器上做一些配置。我在服务器上的任何地方都找不到任何 .md
文件。唯一的 openssl.cnf
文件位于一个奇怪的目录中 (/etc/pki/tls
)。我是否需要在其他地方创建一个新的 openssl.cnf
文件?
最佳答案
这应该做您想做的事情(使用上面建议的 BouncyCaSTLe PEMReader)——获取 PEM 编码的私钥 + 证书,并输出 PKCS#12 文件。对用于保护私钥的 PKCS12 使用相同的密码。
public static byte[] pemToPKCS12(final String keyFile, final String cerFile, final String password) throws Exception {
// Get the private key
FileReader reader = new FileReader(keyFile);
PEMReader pem = new PEMReader(reader, new PasswordFinder() {
@Override public char[] getPassword() {
return password.toCharArray();
}
});
PrivateKey key = ((KeyPair)pem.readObject()).getPrivate();
pem.close();
reader.close();
// Get the certificate
reader = new FileReader(cerFile);
pem = new PEMReader(reader);
X509Certificate cert = (X509Certificate)pem.readObject();
pem.close();
reader.close();
// Put them into a PKCS12 keystore and write it to a byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null);
ks.setKeyEntry("alias", (Key)key, password.toCharArray(), new java.security.cert.Certificate[]{cert});
ks.store(bos, password.toCharArray());
bos.close();
return bos.toByteArray();
}
关于java - 使用或不使用 OpenSSL 将 SSL .pem 转换为 .p12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711173/