I have an RSA Private key file in my folder; how do I use it for string type value encryption in C#?
Loading
I have an RSA Private key file in my folder; how do I use it for string type value encryption in C#?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 29, 2023, 5:32 AM EDT
Hello Piyush,
Please try below code:
Function that takes a string value and an RSA private key file path as input, and returns the encrypted value as a Base64-encoded string:
using System; using System.IO; using System.Security.Cryptography; using System.Text; public static string EncryptString(string valueToEncrypt, string privateKeyFilePath) { // Load the private key from file string privateKey = File.ReadAllText(privateKeyFilePath); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); // Convert the string to a byte array byte[] dataToEncrypt = Encoding.UTF8.GetBytes(valueToEncrypt); // Encrypt the data byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false); // Convert the encrypted data to a Base64-encoded string string encryptedValue = Convert.ToBase64String(encryptedData); return encryptedValue; }To use this function, simply call it with the string value you want to encrypt and the file path of the RSA private key:
string valueToEncrypt = "hello world"; string privateKeyFilePath = "path/to/private/key/file.pem"; string encryptedValue = EncryptString(valueToEncrypt, privateKeyFilePath);Thanks
Naimish Makwana
Rajkiran SwainRank #165 · 14.4K reputationPosted Mar 29, 2023, 4:26 PM EDT
using System; using System.Security.Cryptography; using System.Text; class Program { static void Main(string[] args) { string inputString = "Hello, world!"; byte[] inputBytes = Encoding.UTF8.GetBytes(inputString); // Load the RSA private key from file string privateKeyFile = "path/to/private/key.xml"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string privateKeyXml = System.IO.File.ReadAllText(privateKeyFile); rsa.FromXmlString(privateKeyXml); // Encrypt the input string byte[] encryptedBytes = rsa.Encrypt(inputBytes, false); string encryptedString = Convert.ToBase64String(encryptedBytes); Console.WriteLine("Encrypted string: " + encryptedString); } }