我需要在 java 中创建带有密码的证书 pfx 文件。我在 google 中搜索并可以在 http://www.java2s.com/Tutorial/Java/0490__Security/CreatingaSelfSignedVersion3Certificate.htm 中创建证书“cer”文件
我在main中添加代码
FileOutputStream fos = null;
fos = new FileOutputStream("public.cer");
fos.write(cert.getEncoded());
fos.close();
这只在没有密码的情况下有效。
最佳答案
通常 .pfx
或 pkcs12
是一个 keystore ,用于保存公钥、私钥对。此外,如果您在链接示例中使用带有公共(public)证书的 RSA
key 对,通常该证书必须由证书颁发机构颁发,无论如何我想您正在尝试保存自签名证书,为此你必须直接使用 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());
....
正如我通常在 keystore 中所说的那样,您存储 key 对,通常使用:setKeyEntry(String alias, byte[] key, Certificate[] chain)
或 setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
然而,使用上面的代码,您可以将证书存储在 keystore 中,并使用密码保护它。有关更多信息,请查看:java keystore api .
希望对您有所帮助,
关于java - 如何在 java 中创建证书 pfx 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311678/