首页 > 解决方案 > How do I read RSA public key from PEM file and use it to encrypt in BouncyCastle in C#?

问题描述

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?

标签: c#.net-corecryptographyrsabouncycastle

解决方案


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 ...
        }
    }
}

推荐阅读