如何在Java中创建证书PFX文件?

3
1个回答

3
通常,.pfxpkcs12是密钥库,用于保存公共、私人密钥对。此外,如果您使用带有公共证书的RSA密钥对(例如您链接示例中),通常此证书必须由证书颁发机构颁发。无论如何,我想您试图保存自签名证书,为此您必须使用java.security.KeyStore类而不是直接使用FileOutputStream,以下是一个示例:
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

....

X509Certificate cert = // your certificate...
// generate a keystore instance
KeyStore ks = KeyStore.getInstance("PKCS12");
// save your cert inside the keystore
ks.setCertificateEntry("YourCertAlias", cert);
// create the outputstream to store the keystore
FileOutputStream fos = new FileOutputStream("/your_path/keystore.pfx");
// store the keystore protected with password
ks.store(fos, "yourPassword".toCharArray());

....

正如我所说,通常在密钥库中存储密钥对,通常使用以下方法:setKeyEntry(String alias, byte[] key, Certificate[] chain)setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)。但是,使用上面的代码,您可以将证书存储在受密码保护的密钥库中。有关更多信息,请参阅:java keystore api
希望这可以帮助到您,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接