转换PEM格式的私钥

时间:2013-01-20 15:09:04

标签: java ssl openssl ssl-certificate x509certificate

我创建了一个带有Java代码的自签名证书,并添加到KeyStore中。现在我想将创建的私钥和证书导出为PEM格式的文​​件。没有任何第三方库,是否有可能实现这一目标?以下是我用于创建自签证书的代码。

  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格式的文​​件的建议都会非常有用。

2 个答案:

答案 0 :(得分:4)

您使用Certificate.getEncoded()Key.getEncoded()获取DER并手动执行base 64编码和页眉/页脚,例如使用DatatypeConverter.printBase64Binary()或其他方式。类似的东西:

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";

答案 1 :(得分:0)

在Android上,您可以使用以下Kotlin扩展功能:

import android.util.Base64
import java.security.PublicKey

fun PublicKey.toPemString(): String {
    val publicKeyBase64: String = Base64.encodeToString(this.encoded, Base64.NO_WRAP)
    return publicKeyBase64.chunked(64).joinToString(
        separator = "\n",
        prefix = "-----BEGIN PUBLIC KEY-----\n",
        postfix = "\n-----END PUBLIC KEY-----\n"
    )
}