title: How do I convert a PEM encoded X509 certificate to Org.BouncyCastle.X509.X509Certificate in C#
body: <p>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)</p>
  
  <p>This is what works most of the time:</p>
  
  <pre><code>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);
      }
  </code></pre>
  
  <p>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).  </p>