java 将私钥转换为 PEM 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14425875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:13:16  来源:igfitidea点击:

Convert private key in PEM format

javasslopensslssl-certificatex509certificate

提问by Lolly

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.

我已经用 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
    }       
}

Any suggestion of how to export the key and certificate into file with PEM format will be really helpful.

关于如何将密钥和证书导出为 PEM 格式的文件的任何建议都将非常有帮助。

回答by Daniel Roethlisberger

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:

您使用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";

回答by Anup

Thanks Daniel Roethlisberger, for your reply. I got great help from your reply..

感谢 Daniel Roethlisberger 的回复。我从你的回复中得到了很大的帮助..

Implements in Java as below

在Java中实现如下

String encodedString = "-----BEGIN PRIVATE KEY-----\n";
            encodedString = encodedString+Base64.getEncoder().encodeToString(Enrollment2.getKey().getEncoded())+"\n";
            encodedString = encodedString+"-----END PRIVATE KEY-----\n";