title: Generate X.509 SubjectPublicKeyInfo/OpenSSL PEM public key from self-signed certificate
body: <p>I'm building a stub for a third-party API. Requests made to the third-party have to be encrypted using a public key provided. As part of the stub I would like to decrypt the incoming request.</p>
  
  <p>I plan on changing the public key my calling code uses so that I can decrypt it using my private key.</p>
  
  <p>I have a self-signed certificate that's being used on other parts of the application that I was hoping I could just re-use.</p>
  
  <p>The problem I'm having is getting the public key out of the certificate in the format I need.</p>
  
  <p>Based on a couple of answers by Ian Boyd (<a href="https://stackoverflow.com/a/13104466/648938">this one</a> and <a href="https://stackoverflow.com/a/29707204/648938">this one</a>), the format I need to get the public key into is "<strong>X.509 SubjectPublicKeyInfo/OpenSSL PEM</strong>", that is the format of the key I receive from my third-party. For example:</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcZ/r0nvJyHUUstIB5BqCUJ1CC
  Cd1nzle4bEpPQJ/S0Wn7mV2FDAeh+UcbVhZu9n+5zypYNjeZKapPqBLoT8eCK51y
  Kpzeb8LuEm3P8PK4xN18XBrIF1GprN8IIgSdK9f5SwnemutcURrY+PlWnvj7N5s/
  03RlJA3/NHVXpPW/VQIDAQAB
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>I've tried using the <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.getpublickey(v=vs.110).aspx" rel="nofollow noreferrer">X509Certificate2.GetPublicKey</a> method, and then <code>base64</code> encoding it, but that gives me the key in "<strong>PEM DER ASN.1 PKCS#1 RSA</strong>" format.</p>
  
  <p>Does anyone know how I can get the public key in the format I need? I don't necessarily need the key in code, I just need a string value I can store in my database.</p>
  
  <p>My certificate/private/public/cryptography knowledge is limited to any help would be much appreciated!</p>