Code, JavaEE

Extract Public Key From Signed Certificate

Recently, on a project, I had the task of extracting the public key from a signed RSA certificate and converting it to PEM format. The following code demonstrates one way to do this…


private synchronized String getPublicKeyOutOfCertificate(String signedCertificate) {
 String ret = null;
 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 final String BASEPATH = "/apps/tempdir/certTmp";

final String PATH = String.format("%s%s%s", BASEPATH, UUID.randomUUID().toString(), ".pem");

 PEMParser pemReader = null;
 try {

Object obj;
 try (FileWriter fileWriter = new FileWriter(PATH, false)) {
 fileWriter.write(signedCertificate.trim());
 }

try (FileReader fileReader = new FileReader(PATH)) {
 pemReader = new PEMParser(fileReader);
 obj = pemReader.readObject();
 }

X509CertificateHolder certificateHolder =
 ((X509CertificateHolder) obj);
 JcaX509CertificateConverter jcaConvertor =
 new JcaX509CertificateConverter();

jcaConvertor.setProvider("BC");

X509CertificateObject certificateObj =
 (X509CertificateObject) jcaConvertor
 .getCertificate(certificateHolder);

if (certificateObj != null) {
 ret = convertToPem(certificateObj);
}

} catch (CertificateException | IOException ex) {
 if (ex instanceof IOException) {
// handle the exception
 } else {
// handle the exception
 }
 return ret;
 } finally {
 File fileToDelete = new File(PATH);
 System.gc();
 if (fileToDelete.delete()) {
 LOG.info("File -> {} deleted", PATH);
 } else {
 LOG.info("File -> {} NOT deleted", PATH);
 }
 }

return ret;
 }

public String convertToPem(X509CertificateObject publicKey) {

String code = "-----BEGIN PUBLIC KEY-----\n";
 code += new String(new Base64().encode(publicKey.getPublicKey().getEncoded()));
 code += "-----END PUBLIC KEY-----";

return code;
 }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s