C#RSA非对称加解密
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.Globalization; 8 using System.IO; 9 10 /// <summary> 11 ///RSA 的摘要说明 12 /// </summary> 13 public class RSA 14 { 15 public RSA() 16 { 17 // 18 //TODO: 在此处添加构造函数逻辑 19 // 20 21 } 22 #region RSA非对称加解密 密钥保存在密钥容器,密钥容器保存在计算机的密钥库中 23 24 //public static RSACryptoServiceProvider rsa; 25 //static byte[] cipherbytes;//密码字节 26 //static string PublicAndPrivateKey = null; //私鈅变量 27 //static string PublicKey = null; //公钥变量 28 29 static RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); 30 //static RSAParameters rsaParamsExcludePrivate = rsa.ExportParameters(false); 31 //static RSAParameters rsaParamsIncludePrivate = rsa.ExportParameters(true); 32 33 static string PPKey; //私鈅变量 34 static string PKey; //公钥变量 35 36 37 private static void CreateRSAcsp() 38 { 39 //实例化CspParameters对象 40 41 CspParameters cspPara = new CspParameters(); 42 43 //指定CspParameters对象实例的名称 44 45 cspPara.KeyContainerName = "key_container_test"; 46 47 //设置密钥类型为Exchange 48 49 cspPara.KeyNumber = 1; 50 51 //设置密钥容器保存到计算机密钥库(默认为用户密钥库) 52 53 cspPara.Flags = CspProviderFlags.UseMachineKeyStore; 54 55 //实例化RSA对象的时候,将CspParameters对象作为构造函数的参数传递给RSA对象, 56 57 //如果名称为key_container_test的密钥容器不存在,RSA对象会创建这个密钥容器; 58 59 //如果名称为key_container_test的密钥容器已经存在,RSA对象会使用这个密钥容器中的密钥进行实例化 60 61 //RSACryptoServiceProvider rsaPro = new RSACryptoServiceProvider(cspPara); 62 63 rsa = new RSACryptoServiceProvider(cspPara); 64 } 65 66 67 /// <summary> 68 /// RSA加密 69 /// </summary> 70 /// <param name="EnStr">要加密的字符串</param> 71 /// <returns></returns> 72 public static string RSAEncrypt1(string EnStr) 73 { 74 75 CreateRSAcsp(); 76 RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider(); 77 _rsa.ImportParameters(rsa.ExportParameters(false));//导入公钥 78 byte[] byteData = Encoding.UTF8.GetBytes(EnStr); 79 byte[] EncryptedData = rsa.Encrypt(byteData, false); 80 string result = BitConverter.ToString(EncryptedData); 81 return result; 82 } 83 84 /// <summary> 85 /// RSA解密 86 /// </summary> 87 /// <param name="EeStr">要解密密的字符串</param> 88 /// <returns></returns> 89 public static string RSADecrypt1(string EeStr) 90 { 91 92 string[] sInput = EeStr.Split("-".ToCharArray()); 93 byte[] data = new byte[sInput.Length]; 94 for (int i = 0; i < sInput.Length; i++) 95 { 96 data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); 97 } 98 CreateRSAcsp(); 99 rsa.ImportParameters(rsa.ExportParameters(true)); //导入私钥 100 byte[] DecryptedData = rsa.Decrypt(data, false); 101 string str = string.Empty; 102 str = Encoding.UTF8.GetString(DecryptedData); 103 return str; 104 } 105 106 #endregion 107 108 }