C# – RSA Encryption & Decryption with Certificate
web.conf |
<?xml version="1.0" encoding="utf-8" ?> <configuration> … … <appSettings> <add key="CertFilePath" value="G:\cert\wcfserver.pfx" /> <add key="CertFilePassword" value="wcfserver_passwd" /> </appSettings> </configuration> |
Library/RSACryptoService.cs |
using System; using System.Text; using System.Configuration; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography; namespace RSATest.Library { public class RSACryptoService { private string CertFilePath { get; set; } private string CertFilePassword { get; set; } private X509Certificate2 cert; RSACryptoServiceProvider rsa; public RSACryptoService() { this.CertFilePath = ConfigurationManager.AppSettings["CertFilePath"].ToString(); this.CertFilePassword = ConfigurationManager.AppSettings["CertFilePassword"].ToString(); this.cert = new X509Certificate2(CertFilePath, CertFilePassword); this.rsa = (RSACryptoServiceProvider)cert.PrivateKey; } public string Encryption(string content) { return Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(content), false), Base64FormattingOptions.InsertLineBreaks); } public string Decryption(string encryptString) { return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(encryptString), false)); } } } |
Main.cs |
using System; using RSATest.Library; namespace RSATest { class Main { static void Main(string[] args) { RSACryptoService EnService = new RSACryptoService(); RSACryptoService DeService = new RSACryptoService(); String PlainText = "PlainText"; String En = ""; String De = ""; Console.WriteLine(PlainText); En = EnService.Encryption("PlainText"); Console.WriteLine(En); De = DeService.Decryption(En); Console.WriteLine(De); Console.ReadLine(); } } } |