title: Read RSA Public Key from x509 Certificate Bytes in C#
body: <p>In C#, I'm retrieving an RSA public key from a HTTP request and it gives me the key encoded in base64.</p>
  
  <pre><code>WebClient webClient = new WebClient();
  string rsaPublicKeyBase64 = webClient.DownloadString("http://localhost:8000/getkey");
  // rsaPublicKeyBase64 = LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFEQ0JpUUtCZ1FEdDAwcXQ2Zi9UUXdMQmVsVExRdVlXb05xSQoxbmRkcFpaOGh0WWs4d0NLbmFuRFJpWkJ1NVo5NnBNT01yNi84RS9JUzB0amV4WGdsVjh0WFlKK0NKc1lDUHhoCnBDUkduUW9rYkE2MnpOODVXNEROVUNMQ0cyMXlXcndscFhjSmxLYkY2dFhxdmd3TGRQb2RwZzUwY3RrWkI4R0UKbDBLS3VOV3JHZXRad045V0NRSURBUUFCCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo=
  </code></pre>
  
  <p>I then decode the base 64 RSA public key.</p>
  
  <pre><code>byte[] rsaPublicKey = Convert.FromBase64String(rsaPublicKeyBase64);
  /*
  -----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDt00qt6f/TQwLBelTLQuYWoNqI
  1nddpZZ8htYk8wCKnanDRiZBu5Z96pMOMr6/8E/IS0tjexXglV8tXYJ+CJsYCPxh
  pCRGnQokbA62zN85W4DNUCLCG21yWrwlpXcJlKbF6tXqvgwLdPodpg50ctkZB8GE
  l0KKuNWrGetZwN9WCQIDAQAB
  -----END PUBLIC KEY-----
  */
  </code></pre>
  
  <p>My next step is to convert this <code>byte[]</code> containing my RSA public key certificate into type <code>RSACryptoServiceProvider</code>. I've found answers online, but none seem to work for me.</p>
  
  <p>Here's what I currently have (which does not work).</p>
  
  <pre><code>string rsaPublicKeyFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
  X509Certificate2 cert = null;
  try {
      File.WriteAllBytes(rsaPublicKeyFile, rsaPublicKey);
      cert = new X509Certificate2(rsaPublicKeyFile);
  } finally {
      File.Delete(rsaPublicKeyFile);
  }
  </code></pre>
  
  <p>I receive an unhandled exception error shown in the screenshot below.</p>
  
  <p><a href="https://i.stack.imgur.com/umGP0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/umGP0.png" alt="Unhandled Exception Error"></a></p>
  
  <pre><code>System.Security.Cryptography.CryptographicException: 'Cannot find the requested object.
  </code></pre>