在.NET中读取PEM RSA私钥
在.NET中,您可以方便地读取PEM RSA私钥并实例化RSACryptoServiceProvider解密用相应的公共加密的数据key.
.NET 5 支持
.NET 5 现在为此任务提供内置支持。要使用它,请按照以下步骤操作:
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 解决方案
.NET 5 之前,BouncyCastle 库提供了一个解决方案:
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私钥进行解密?的详细内容。更多信息请关注PHP中文网其他相关文章!