RSA Private Key Retrieval in .NET from PEM Format
In .NET, reading a PEM-formatted RSA private key and initializing an RSACryptoServiceProvider instance for decrypting data encrypted using the corresponding public key requires specific steps. This article outlines two approaches to accomplish this task.
.NET 5 and Later
Starting with .NET 5, a built-in capability is available to read PEM private keys:
var privateKey = @"-----BEGIN RSA PRIVATE KEY----- { the full PEM private key } -----END RSA PRIVATE KEY-----"; var rsa = RSA.Create(); rsa.ImportFromPem(privateKey.ToCharArray());
Pre-Installed Libraries
For earlier versions of .NET or if the built-in functionality is not suitable, external libraries like BouncyCastle provide 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));
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3