Wednesday, July 15, 2015

PEM File Creation

PEM:Privacy Enhanced Mail is a Base64 encoded DER certificate
PEM files are used to represent Certificate/PrivateKey in an understandable format. They have a distinct header and footer for every key, where the body is composed of Base64 encoded Key.
They are represented as shown below for (Certificate/PrivateKey/Certificate Signing Request/PublicKey)
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCpF26VoB9/Au3Ct/dBFW5kfXFU8IkK+G3CG4slkVX2mwBtvLyb
mFAuQ3RXvmX6tZxeUgwN7m+pZH+Y94lgAIpvcnzBEh8FFxwu0jy17uw+4ler5Soy
YRGV8TYOeQHqoHS44clTG28T2RYy9lkRqTIkkCyo5ViyD7GVQVUgjR31LQIDAQAB
AoGAFmkioPYd9ol+1aXoQVoDzZHKqYVPxIJ0mZto78u5ZvvYLLMtFDo1tkv+aXq0
rWvQk7ewHVCSwBKvzqhQLscjkbZqBdhnkBsyDQTcTQ+0sf8RGDHhBz2A1gGrBFhB
rWc9wGuk7CFHUCrUL0ZXBquMM1KCd/+Fdg2+OQzcoJd9/AECQQDkLdyiaG4Y/lFM
i4wtIf9rNVP4a1jHcYk1Ll7wvymY+v0e9zNVqKbkHaZ4/tyvD3MzVXZCByJZoFu4
sCWRK9WBAkEAvbVF3E7jxrQNTNRqLyQW6v0cmNSCSUfDkYANRuO+d6xvvT2HgrYs
SiL8h4qDLkbM/LTvf9lxb8vSlUSt/3ctrQJAP70767YmQx8PkMVOg/ECS21bJoK+
CwCBJnTsmm2b7hr2iCbflScGb6SEsznmZZR4Rrex0CH0C3tLA91YsSPAgQJAa1Wc
6UFZbpuAyu+EBJgOv3XmMDJMZNnNtQ0Wdf11TpCpyBCAE1yvQmL5LlcYUZ6NbI2S
1Gta2z4fL4VkTR5JIQJAQE6QBPguRRYLFyDa6db+QyeJ1iBHy3I8XvK9bem+Dsby
Km2l2KzLk3IpIEniqjLcoCQzFd5jp8m5VfjMx1doQQ==
-----END RSA PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpF26VoB9/Au3Ct/dBFW5kfXFU
8IkK+G3CG4slkVX2mwBtvLybmFAuQ3RXvmX6tZxeUgwN7m+pZH+Y94lgAIpvcnzB
Eh8FFxwu0jy17uw+4ler5SoyYRGV8TYOeQHqoHS44clTG28T2RYy9lkRqTIkkCyo
5ViyD7GVQVUgjR31LQIDAQAB
-----END PUBLIC KEY-----


-----BEGIN CERTIFICATE-----
MIIBmjCCAQMCBgFOkeZMojANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhSYXZp
VGVqYTAeFw0xNTA3MTQxMzI3NDVaFw0xNTA2MjkyMTQ1NTZaMBMxETAPBgNVBAMT
CFJhdmlUZWphMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpF26VoB9/Au3C
t/dBFW5kfXFU8IkK+G3CG4slkVX2mwBtvLybmFAuQ3RXvmX6tZxeUgwN7m+pZH+Y
94lgAIpvcnzBEh8FFxwu0jy17uw+4ler5SoyYRGV8TYOeQHqoHS44clTG28T2RYy
9lkRqTIkkCyo5ViyD7GVQVUgjR31LQIDAQABMA0GCSqGSIb3DQEBCwUAA4GBAIh6
cNhWToRwhaJBykHXPqiaqPDA8n0xtq65dBiUQWOKeoXw0I7+LKUUzfHfb4wGZoLK
W2rBnNCY1BtpasqtAkdZ/Q+keJQd9xBcPqnKGUEqxxX7omB7cKYuhw9C+rGn/K1J
Ci1xlYBWuRsMd3A064fSHV0Adu+ru9YaWyS5+aLU
-----END CERTIFICATE-----


Java Program to generate PEM files.
package bc;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V1CertificateGenerator;

public class PEMWrite {
    public static void main(String[] args) throws Exception {
        generateSelfSignedX509Certificate();
    }

    static {
        // adds the Bouncy castle provider to java security
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * Generate a self signed X509 certificate with Bouncy Castle.
     */
    static void generateSelfSignedX509Certificate() throws Exception {

        // yesterday
        Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
        // in 2 years
        Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);

        // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(1024, new SecureRandom());

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // GENERATE THE X509 CERTIFICATE
        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal dnName = new X500Principal("CN=RaviTeja");
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setSubjectDN(dnName);
        certGen.setIssuerDN(dnName); // use the same
        certGen.setNotBefore(validityBeginDate);
        certGen.setNotAfter(validityEndDate);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
        System.out.println(cert);

        // PEM format representing Certificate
        PEMWriter pemWriter = new PEMWriter(new PrintWriter(System.out));
        pemWriter.writeObject(cert);
        pemWriter.flush();

        //Loads Private Key as PEM format into private_key.pem file
        File file = new File("private_key.pem");
        PEMWriter pw1 = new PEMWriter(new FileWriter(file));
        pw1.writeObject(keyPair.getPrivate());
        pw1.flush();
        pw1.close();

        //PEM format representing PrivateKey
        pemWriter.writeObject(keyPair.getPrivate());
        pemWriter.flush();

        //PEM format representing PublicKey
        pemWriter.writeObject(keyPair.getPublic());
        pemWriter.flush();
        pemWriter.close();

    }
}