Friday, 14 September 2012

Read X509 Certificate in Java

Reading an X509 certificate in Java can be done using the following code. I used it specifically for obtaining a reference to the Apple WWDR certificate, but generally speaking, this will work for reading any certificate in X509 format.

import java.security.cert.*;
import java.io.*;
import org.apache.commons.io.IOUtils;
import java.security.NoSuchProviderException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;


public static X509Certificate readWWDRCertificate(String keyFile) throws IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException
{
FileInputStream fis = null;
ByteArrayInputStream bais = null;
try 
{
// use FileInputStream to read the file
fis = new FileInputStream(keyFile);

// read the bytes
byte value[] = new byte[fis.available()];
fis.read(value);
bais = new ByteArrayInputStream(value);

// get X509 certificate factory
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

// certificate factory can now create the certificate 
return (X509Certificate)certFactory.generateCertificate(bais);
}
finally 
{
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(bais);
}
}

The parameter you pass in should be the absolute location of the certificate file. In my case, my String parameter is something like "C:\\cert\AppleWWDRCA.cer".