using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Globalization;
using System.IO;
/// <summary>
///RSA 的摘要说明
/// </summary>
public class RSA
{
public RSA()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region RSA非对称加解密 密钥保存在密钥容器,密钥容器保存在计算机的密钥库中
//public static RSACryptoServiceProvider rsa;
//static byte[] cipherbytes;//密码字节
//static string PublicAndPrivateKey = null; //私鈅变量
//static string PublicKey = null; //公钥变量
static RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//static RSAParameters rsaParamsExcludePrivate = rsa.ExportParameters(false);
//static RSAParameters rsaParamsIncludePrivate = rsa.ExportParameters(true);
static string PPKey; //私鈅变量
static string PKey; //公钥变量
private static void CreateRSAcsp()
{
//实例化CspParameters对象
CspParameters cspPara = new CspParameters();
//指定CspParameters对象实例的名称
cspPara.KeyContainerName = "key_container_test";
//设置密钥类型为Exchange
cspPara.KeyNumber = 1;
//设置密钥容器保存到计算机密钥库(默认为用户密钥库)
cspPara.Flags = CspProviderFlags.UseMachineKeyStore;
//实例化RSA对象的时候,将CspParameters对象作为构造函数的参数传递给RSA对象,
//如果名称为key_container_test的密钥容器不存在,RSA对象会创建这个密钥容器;
//如果名称为key_container_test的密钥容器已经存在,RSA对象会使用这个密钥容器中的密钥进行实例化
//RSACryptoServiceProvider rsaPro = new RSACryptoServiceProvider(cspPara);
rsa = new RSACryptoServiceProvider(cspPara);
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="EnStr">要加密的字符串</param>
/// <returns></returns>
public static string RSAEncrypt1(string EnStr)
{
CreateRSAcsp();
RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider();
_rsa.ImportParameters(rsa.ExportParameters(false));//导入公钥
byte[] byteData = Encoding.UTF8.GetBytes(EnStr);
byte[] EncryptedData = rsa.Encrypt(byteData, false);
string result = BitConverter.ToString(EncryptedData);
return result;
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="EeStr">要解密密的字符串</param>
/// <returns></returns>
public static string RSADecrypt1(string EeStr)
{
string[] sInput = EeStr.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
CreateRSAcsp();
rsa.ImportParameters(rsa.ExportParameters(true)); //导入私钥
byte[] DecryptedData = rsa.Decrypt(data, false);
string str = string.Empty;
str = Encoding.UTF8.GetString(DecryptedData);
return str;
}
#endregion
}