Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert private key in PEM format

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
    }       
}

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

like image 460
Lolly Avatar asked Jan 20 '13 15:01

Lolly


People also ask

Does PEM format contain private key?

The typical PEM files are: key. pem contains the private encryption key. cert.

What is PEM format private key?

A . pem file is a container format that may just include the public certificate or the entire certificate chain (private key, public key, root certificates): Private Key. Server Certificate (crt, puplic key)

How do I convert a .PFX file to .PEM format including private key?

Navigate to Traffic Management, Select the SSL node. Click the Import PKCS#12 link. Specify a file name you want for the PEM certificate in the Output File Name field. Click Browse and select the PFX certificate that you want to convert to PEM format.


1 Answers

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";
like image 124
Daniel Roethlisberger Avatar answered Oct 02 '22 04:10

Daniel Roethlisberger