September 15, 2016

Convert a PEM-formatted String to a java.security.cert.X509Certificate

public static java.security.cert.X509Certificate parseCertificate(String certPEM)
        throws IOException, java.security.cert.CertificateException {

    byte[] decoded = new sun.misc.BASE64Decoder()
            .decodeBuffer(certPEM.replaceAll(sun.security.provider.X509Factory.BEGIN_CERT, "")
                    .replaceAll(sun.security.provider.X509Factory.END_CERT, ""));

    return (java.security.cert.X509Certificate) java.security.cert.CertificateFactory.getInstance("X.509")
            .generateCertificate(new ByteArrayInputStream(decoded));
}

No comments: