c# - 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?
解决方案
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 ...
}
}
}
推荐阅读
- javascript - 如何使用 w2ui 在组合框中获取字符串?
- android - 反应本机android应用程序中的图像显示
- python - 将两个神经网络的损失函数与一些权重相结合并同时训练它们
- makefile - “make”如何确定使用哪个链接器?
- cloudsim - 如何计算VM的功耗?
- azure - 具有静态 IP 和自定义证书/AKS 入口问题的 AKS
- c - 当我释放分配的内存时出现 munmap_chunk() 错误
- javascript - 如何使用 javascript/jquery 在 arrayList 中存储选中项的值?
- java - Springboot jdbc/jpa
- autodesk-forge - Forge Viewer - 如何输出网格信息日志?