title: Reading PEM RSA Public Key Only using Bouncy Castle
body: <p>I am trying to use C# to read in a <code>.pem</code> file that contains only a RSA public key.  I do not have access to the private key information, nor does my application require it.  The file <code>myprivatekey.pem</code> file begins with </p>
  
  <p><code>-----BEGIN PUBLIC KEY-----</code>
  and ends with 
  <code>-----END PUBLIC KEY-----</code>.</p>
  
  <p>My current code is as follows:</p>
  
  <pre><code>    Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair;
  
      using (var reader = File.OpenText(@"c:\keys\myprivatekey.pem"))
          keyPair = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
  </code></pre>
  
  <p>However the code throws an <code>InvalidCastException</code> with the message </p>
  
  <blockquote>
    <p>Unable to cast object of type
    'Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters' to type
    'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair'.</p>
  </blockquote>
  
  <p>How can I use Bouncy Castle's <code>PemReader</code> to read only a public key, when no private key information is available?</p>