java - 如何在 java 中创建证书 pfx 文件?

标签 java security certificate pfx

我需要在 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();

这只在没有密码的情况下有效。

最佳答案

通常 .pfxpkcs12 是一个 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/

相关文章:

azure - 使用 key 保管库生成客户端证书

html - HTML5 本地存储对信用卡信息的安全影响是什么

java - 自动删除已删除对象的对象

java - SQL 返回计数字段的总和。不允许我删除 GroupBy

java - 处理 primefaces 文本区域提交值中的换行符

security - 在 iframe 中设置 cookie - 不同的域

php - 使用 SHA-256 进行 CodeIgniter 哈希

.net - 使用客户端证书身份验证创建 .NET Web 服务

ios - 内部分布概况

java - 如何对@Any 注释属性进行双向映射?