如何从 .NET 读取 PEM RSA 私钥

How to read a PEM RSA private key from .NET(如何从 .NET 读取 PEM RSA 私钥)
本文介绍了如何从 .NET 读取 PEM RSA 私钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PEM 格式的 RSA 私钥,有没有一种直接的方法可以从 .NET 中读取它并实例化一个 RSACryptoServiceProvider 解密用相应公钥加密的数据?

I've got an RSA private key in PEM format, is there a straight forward way to read that from .NET and instantiate an RSACryptoServiceProvider to decrypt data encrypted with the corresponding public key?

推荐答案

更新03/03/2021

.NET 5 现在支持此功能.

Update03/03/2021

.NET 5 now supports this out of the box.

要尝试下面的代码片段,请在 http://travistidwell.com/生成密钥对并加密一些文本jsencrypt/demo/

To try the code snippet below, generate a keypair and encrypt some text at http://travistidwell.com/jsencrypt/demo/

var privateKey = @"-----BEGIN RSA PRIVATE KEY-----
{ the full PEM private key } 
-----END RSA PRIVATE KEY-----";

var rsa = RSA.Create();
rsa.ImportFromPem(privateKey.ToCharArray());

var decryptedBytes = rsa.Decrypt(
    Convert.FromBase64String("{ base64-encoded encrypted string }"), 
    RSAEncryptionPadding.Pkcs1
);

// this will print the original unencrypted string
Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes));

原答案

我解决了,谢谢.万一有人感兴趣,bouncycastle 成功了,只是因为我缺乏知识而花了我一些时间和文档.这是代码:

Originalanswer

I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:

var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded
 
AsymmetricCipherKeyPair keyPair; 
 
using (var reader = File.OpenText(@"c:myprivatekey.pem")) // file containing RSA PKCS1 private key
    keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); 
 
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private); 
 
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); 

这篇关于如何从 .NET 读取 PEM RSA 私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)