Home > Backend Development > C++ > How to Read and Use a PEM RSA Private Key in .NET?

How to Read and Use a PEM RSA Private Key in .NET?

Mary-Kate Olsen
Release: 2025-01-06 11:38:41
Original
200 people have browsed it

How to Read and Use a PEM RSA Private Key in .NET?

Reading a PEM RSA Private Key in .NET

In .NET, there are several approaches to read a PEM RSA private key and instantiate an RSACryptoServiceProvider for decryption purposes.

Using .NET 5 and Above

For .NET 5 and later versions, support for reading PEM RSA private keys is built-in. The following code sample demonstrates how to do this:

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));
Copy after login

Using Bouncy Castle Library

For older versions of .NET, you can utilize the Bouncy Castle library to read PEM RSA private keys. Here's an example:

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)); 
Copy after login

The above is the detailed content of How to Read and Use a PEM RSA Private Key in .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template