問題描述
我有一個 PEM
格式的 RSA
私鑰,有沒有一種直接的方法可以從 .NET 中讀取它并實例化一個 RSACryptoServiceProvider
解密用相應(yīng)公鑰加密的數(shù)據(jù)?
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 現(xiàn)在支持此功能.
Update 03/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 成功了,只是因為我缺乏知識而花了我一些時間和文檔.這是代碼:
Original answer
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));
這篇關(guān)于如何從 .NET 讀取 PEM RSA 私鑰的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!