Reading a PEM RSA Private Key in .NET
In .NET, you can conveniently read a PEM RSA private key and instantiate an RSACryptoServiceProvider to decrypt data encrypted with the corresponding public key.
.NET 5 Support
.NET 5 now offers built-in support for this task. To utilize it, proceed as follows:
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));
Original BouncyCastle Solution
Before .NET 5, the BouncyCastle library provided a solution:
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));
The above is the detailed content of How to Read and Use a PEM RSA Private Key for Decryption in .NET?. For more information, please follow other related articles on the PHP Chinese website!