using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; namespace RSATest { class Program { static void Main(string[] args) { string content = "这是测试内容!Hellow"; Console.WriteLine(content); content = RSACrypto.Encrypt(content); Console.WriteLine(content); content = RSACrypto.Decrypt(content); Console.WriteLine(content); Console.Read(); } } }
using System; using System.Text; using System.Collections.Generic; using System.Security.Cryptography; namespace UNetwork { /// <summary> /// RSA用途 /// 作用一:私钥签名、公钥验签 /// 作用二:公钥加密、私钥解密 /// </summary> public static class RSACrypto { public static string publicKey; private static string privateKey; private static RSACryptoServiceProvider provider; static RSACrypto() { GenerateKey(); } /// <summary> /// 生成密钥 /// </summary> public static void GenerateKey() { try { provider = new RSACryptoServiceProvider(); publicKey = provider.ToXmlString(false); privateKey = provider.ToXmlString(true); } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// 加密 /// </summary> public static string Encrypt(string content) { try { //设置密钥方式一 //provider.ImportParameters(rsaParameters); //设置密钥方式二 provider.FromXmlString(publicKey); byte[] bytes = Encoding.UTF8.GetBytes(content); bytes = provider.Encrypt(bytes, false); content = Convert.ToBase64String(bytes); } catch (Exception e) { Console.WriteLine(e.ToString()); } return content; } /// <summary> /// 解密 /// </summary> public static string Decrypt(string content) { try { //设置密钥方式一 //provider.ImportParameters(rsaParameters); //设置密钥方式二 provider.FromXmlString(privateKey); byte[] bytes = Convert.FromBase64String(content); bytes = provider.Decrypt(bytes, false); content = Encoding.UTF8.GetString(bytes); } catch (Exception e) { Console.WriteLine(e.ToString()); } return content; } // 通过密钥指数和模数创建密钥参数对象 public static RSAParameters CreateRSAParameters(string Exponent, string Modulus) { RSAParameters rsaParameters = new RSAParameters(); rsaParameters.Exponent = FromHex(Exponent);//指数 rsaParameters.Modulus = FromHex(Modulus);//模数 return rsaParameters; } // 16进制的字符串转表示 转 byte[] public static byte[] FromHex(string hex) { if (string.IsNullOrEmpty(hex) || hex.Length % 2 != 0) throw new ArgumentException("not a hexidecimal string"); List<byte> bytes = new List<byte>(); for (int i = 0; i < hex.Length; i += 2) { bytes.Add(Convert.ToByte(hex.Substring(i, 2), 16)); } return bytes.ToArray(); } } }
运行效果