title: RSA encrypt a string from PEM public key in dotnet core
body: <p>I'm trying to encrypt a string using a PEM public key file in dotnet core (1.1) and my question is:  How do I do this?</p>
  
  <p>I thought this would simply be a case of:</p>
  
  <pre><code>var cert = new X509Certificate2("path_to_public_key.pem");
  using (var rsa = cert.GetRSAPublicKey())
  {
      // encrypt here
  }
  </code></pre>
  
  <p>However, when I try to new up the certificate I get the following error:</p>
  
  <blockquote>
    <p>error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error</p>
  </blockquote>
  
  <p>The PEM file looks like this:</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  ... ANBgkqhkiG9w0BAQEFA ...
  (loads more text)
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>I've checked the pem file and there are no extraneous ^M characters anywhere (as from a suggest cause of the error <a href="https://serverfault.com/a/317038">here</a>).</p>
  
  <p>(I'm on macOS Sierra if that makes any difference)</p>
  
  <p>Any help would be greatly appreciated!</p>