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

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 11:39:41172browse

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

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:

  1. Generate a key pair and encrypt some text using an online tool like http://travistidwell.com/jsencrypt/demo/.
  2. 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!

Statement:
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