问题描述
我有一个 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 私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!