Monday, 24 September 2012

Embedding Certificates into Java unit-tests

I was trying to find a more elegant way of embedding test certificates into my java tests. Spying and mocking only get me so far. Occasionally it is easier to use real certificates and then in integration tests I want to use real data anyway.
I don't want to embed certificate files as files into the test folders so I have been encoding the data as constants.
The trick for doing this is this:
  1. Turn it into Base64 or PEM. For certificates I use PEM and to do this I open the certificate file in windows, choose the details tab, choose "Copy to file", choose base64 as the format and save as a .cer. Then open the file in notepad and copy out the PEM.
    For other types of file (PKCS#7 etc) I just base 64 encode it using something like this:
  2. Embed the data as a constant. I use Dev Studio to do this. Open the text PEM or Base64 file in DevStudio and use the match expression of ^{.*}$ and replacement of \t\t\"\1\\n\"\+. This will turn something like:
    -----BEGIN CERTIFICATE-----
    MIICHTCCAYagAwIBAgIIFW/6AIuFtIwwDQYJKoZIhvcNAQENBQAwRzELMAkGA1UE
    
    Into
        "-----BEGIN CERTIFICATE-----\n"+
        "MIICHTCCAYagAwIBAgIIFW/6AIuFtIwwDQYJKoZIhvcNAQENBQAwRzELMAkGA1UE\n"+
    
    Then you past that into the java as
        private static final String testCertPEM =
        "-----BEGIN CERTIFICATE-----\n"+
        "MIICHTCCAYagAwIBAgIIFW/6AIuFtIwwDQYJKoZIhvcNAQENBQAwRzELMAkGA1UE\n"+
        ...
        "...";
    
  3. Read it back in To turn this into a certificate you need this bit of code (using BouncyCastle)
    private X509Certificate parsePEMCert(String pemCert)
        {
            final Reader reader = new StringReader(pemCert);
            final PEMReader pemReader = new PEMReader(reader,null);
            try
            {
                return (X509Certificate)pemReader.readObject();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }        
        }
    

No comments:

Post a Comment