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

javasslx509certificate

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]

Best Solution

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

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