1

How do I convert a PEM encoded X509 certificate to a Bouncycastle X509Certificate? I receive the PEM encoded X509 certificate (defined in RFC 5280) that represents the issuer of the signing certificate. The PEM encoding format (defined in RFC 1421) requires a line length of 64 characters. The PEM encoded certificate is received through an HttpWebRequest (application/json;charset=utf-8)

This is what works most of the time:

Org.BouncyCastle.X509.X509Certificate pemToX509Certificate(string signature)
    {
        byte[] buffer = GetBytesFromPEM("CERTIFICATE", signature);
        X509CertificateParser parser = new X509CertificateParser();
        Org.BouncyCastle.X509.X509Certificate cert = parser.ReadCertificate(buffer);
        return cert;
    }

    byte[] GetBytesFromPEM(string type, string pem)
    {
        byte[] bytes = Encoding.Default.GetBytes(pem);
        pem = Encoding.UTF8.GetString(bytes);
        string header = String.Format("-----BEGIN {0}-----", type);
        string footer = String.Format("-----END {0}-----", type);
        int start = pem.IndexOf(header) + header.Length;
        int end = pem.IndexOf(footer, start);
        string base64 = pem.Substring(start, (end - start));

        return Convert.FromBase64String(base64);
    }

Is this the correct way to do this? Especially the Encoding.UTF8.GetString part? Because I already specifically tell the HttpWebRequest that the response is UTF8 in StreamReader(response.GetResponseStream(), Encoding.UTF8).

Amedee Van Gasse
  • 7,280
  • 5
  • 55
  • 101
Cerveser
  • 752
  • 8
  • 23
  • As PEM encoding relies on ASCII only, encoding `pem` using the default encoding and decoding the resulting bytes using UTF8 results in the same string as you started with (at least on the common platforms). – mkl Dec 22 '18 at 15:14
  • thanks, so I can remove the first two lines byte[] bytes = Encoding.Default.GetBytes(pem); and pem = Encoding.UTF8.GetString(bytes); – Cerveser Dec 22 '18 at 16:00

1 Answers1

0

See comments, I removed the first two lines:

 protected static byte[] GetBytesFromPEM(string type, string pem)
    {
        string header = String.Format("-----BEGIN {0}-----", type);
        string footer = String.Format("-----END {0}-----", type);
        int start = pem.IndexOf(header) + header.Length;
        int end = pem.IndexOf(footer, start);
        string base64 = pem.Substring(start, (end - start));

        return Convert.FromBase64String(base64);
    }
Cerveser
  • 752
  • 8
  • 23