Reading PEM RSA Public Key Only using Bouncy Castle

cytinus picture cytinus · Jul 5, 2012 · Viewed 33.1k times · Source

I am trying to use C# to read in a .pem 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 myprivatekey.pem file begins with

-----BEGIN PUBLIC KEY----- and ends with -----END PUBLIC KEY-----.

My current code is as follows:

    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();

However the code throws an InvalidCastException with the message

Unable to cast object of type 'Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters' to type 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair'.

How can I use Bouncy Castle's PemReader to read only a public key, when no private key information is available?

Answer

cytinus picture cytinus · Jul 6, 2012

The following code will read a public key from a given filename. The exception handling should be changed for any production code. This method returns an AsymetricKeyParameter:

public Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
    var fileStream = System.IO.File.OpenText(pemFilename);
    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
    var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
    return KeyParameter;
}