以PEM格式转换私钥 [英] Convert private key in PEM format
问题描述
我使用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-----\n" +
DatatypeConverter.printBase64Binary(chain[0].getEncoded())) +
"\n-----END CERTIFICATE-----\n";
keypem = "-----BEGIN RSA PRIVATE KEY-----\n" +
DatatypeConverter.printBase64Binary(privKey.getEncoded())) +
"\n-----END RSA PRIVATE KEY-----\n";
这篇关于以PEM格式转换私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!