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

Jeffrey Chung picture Jeffrey Chung · Mar 16, 2012 · Viewed 57.7k times · Source

How does one create a java.security.cert.X509Certificate instance from a PEM-formatted String? The PEM-formatted String is a HTTP request "SSL_CLIENT_CERT" header value.

ANSWER: Based on mgaert's answer, here's what I wrote in Scala:

val cert = factory.generateCertificate(
    new ByteArrayInputStream(
      Base64.decodeBase64(
        cert.stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----")
      )
    ).asInstanceOf[X509Certificate]

Answer

mgaert picture mgaert · Mar 16, 2012

Decode the Base64 to binary, with some InputStream reading it, then try

CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);