How to Read and Use a PEM RSA Private Key for Decryption in .NET?
Jan 06, 2025 am 11:39 AMReading 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:
- Generate a key pair and encrypt some text using an online tool like http://travistidwell.com/jsencrypt/demo/.
- Use the following code snippet to import the PEM private key and decrypt the ciphertext:
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?

How does the C Standard Template Library (STL) work?
