Convert private key in PEM format(转换 PEM 格式的私钥)
问题描述
我用 Java 代码创建了一个自签名证书并添加到 KeyStore.现在我想将创建的私钥和证书导出到 PEM 格式的文件中.是否有可能在没有任何第三方库的情况下实现这一目标?以下是我用于创建自签名证书的代码.
I have created a self-signed certificate with Java code and added into KeyStore. Now I want to export Private key and Certificate created, into a file in PEM format. Is it possible to achieve this without any third party library ? Below is the code I use for creating self-singed certificate.
public void createSelfSignedSSLCertificate() {
try {
final CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
final X500Name x500Name =
new X500Name(commonName, organizationalUnit, organization, city, state, country);
keypair.generate(keysize);
final PrivateKey privKey = keypair.getPrivateKey();
final X509Certificate[] chain = new X509Certificate[1];
chain[0] = keypair.getSelfCertificate(x500Name, new Date(), validity * 24 * 60 * 60);
final String alias = JettySSLConfiguration.SSL_CERTIFICATE_ALIAS;
keyStore.setKeyEntry(alias, privKey, keyStorePassword.toCharArray(), chain);
} catch (final Exception e) {
// Handle Exception
}
}
任何关于如何将密钥和证书导出为 PEM 格式文件的建议都会非常有帮助.
Any suggestion of how to export the key and certificate into file with PEM format will be really helpful.
推荐答案
你使用Certificate.getEncoded() 和 Key.getEncoded() 获取 DER 并手动执行 base 64 编码和页眉/页脚,例如使用 DatatypeConverter.printBase64Binary() 或其他方式.比如:
You use Certificate.getEncoded() and Key.getEncoded() to get DER and do the base 64 encoding and header/footer manually, e.g. using DatatypeConverter.printBase64Binary() or some other way. Something like:
certpem = "-----BEGIN CERTIFICATE-----
" +
DatatypeConverter.printBase64Binary(chain[0].getEncoded())) +
"
-----END CERTIFICATE-----
";
keypem = "-----BEGIN RSA PRIVATE KEY-----
" +
DatatypeConverter.printBase64Binary(privKey.getEncoded())) +
"
-----END RSA PRIVATE KEY-----
";
这篇关于转换 PEM 格式的私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换 PEM 格式的私钥
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01