1

The C# BouncyCastle contains a class called Org.BouncyCastle.Utilities.IO.Pem.PemReader that seem to take the RSA public key file in PEM format. I looked at this link: how can i convert pem public key to rsa public key with bouncycastle in c#?

But it seemed to be using non-existent method on PemReader called ReadObject. So I wrote following code instead.

var pemReader = new PemReader(File.OpenText(@"...rsa public key file path ..."));
var pemObject = pemReader.ReadPemObject();
var rsaPublicKeyBytes = pemObject.Content;

Once I get the RSA public bytes, I am not sure how to proceed further. I want to be able to do following:

var rsaCipher = new RsaEngine();
var oaepEncoding = new OaepEncoding(rsaCipher, new Sha256Digest());
var publicKey = new RsaKeyParameters(...);
oaepEncoding.Init(true, publicKey);
var actualEncryptedBytes = oaepEncoding.ProcessBlock(plainBytes, 0, plainBytes.Length);

I guess I am not sure about how to construct RsaKeyParameters with RSA public bytes. Can someone point me in the right direction? Or am I totally going the wrong way here?

nisarg parekh
  • 413
  • 4
  • 23
Raghu
  • 2,859
  • 4
  • 33
  • 65
  • Did you tried using PEMReader object inside stream `code` using (var keyreader = new StringReader(publickey)) { var pemReader = new PemReader(keyreader); var y = (RsaKeyParameters)pemReader.ReadObject(); } `code` – user1010186 Jun 07 '19 at 09:16

1 Answers1

5

You're using the wrong PemReader, you want the one from Org.BouncyCastle.OpenSsl.

EDIT: For some reason OP is insistent that this class has no ReadObject method. It does, and it can be seen here.

Like this:

using System;
using System.IO;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

namespace ScratchPad
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var pemReader = new PemReader(File.OpenText(@"/Users/horton/tmp/key-examples/myserver_pub.pem"));
            var pemObject = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)pemReader.ReadObject();
            var rsa = DotNetUtilities.ToRSA(pemObject);
            // ... more stuff ...
        }
    }
}
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • Version 1.8.5 of BouncyCastle does not have ReadObject method on PemReader class. There was no equivalent method that would give me RsaKeyParameters. Any suggestions? In other words, the ReadPemObject method returns PemObject which is not castable to RsaKeyParameters. – Raghu Jun 07 '19 at 16:54
  • 1
    Once again: you are using **the wrong PemReader class**. Please re-read the first line of my answer. Line 85 of `Org.BouncyCastle.OpenSsl.PemReader is: `public object ReadObject()`. – President James K. Polk Jun 07 '19 at 18:40