Converting a private key in PEM format

I created a self signed certificate with Java code and added it to KeyStore. Now I want to export the private key and generated certificate to a PEM file. Is it possible to achieve this without any third party library? Below is the code I am using to generate a self-service 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 on how to export the key and certificate to a PEM file would be really helpful.

+3


source to share


1 answer


You use Certificate.getEncoded () and Key.getEncoded () to get DER and do base 64 encoding and header / footer manually, for example 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";

      

+3


source







All Articles