<summary>
/// DES加密解密算法。
/// </summary>
public static class DESEncrypt
{
/**/
/// <summary>
/// 对称加密解密的密钥
/// </summary>
public static string EncryptKey = "12345678";//只能8位
/**/
/// <summary>
/// DES加密
/// </summary>
/// <param name="encryptString"></param>
/// <returns></returns>
public static string Encrypt(string encryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptKey);
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
/**/
/// <summary>
/// DES解密
/// </summary>
/// <param name="decryptString"></param>
/// <returns></returns>
public static string Decrypt(string decryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptKey);
byte[] keyIV = keyBytes;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
}
/// <summary>
/// RSA加密解密算法
/// </summary>
public static class RSAEncrypt
{
/**/
/// <summary>
/// 对称加密解密的密钥
/// </summary>
public static string EncryptKey = "123465654";
public static CspParameters param;
/**/
/// <summary>
/// DES加密
/// </summary>
/// <param name="encryptString"></param>
/// <returns></returns>
public static string Encrypt(string encryptString)
{
param = new CspParameters();
param.KeyContainerName = EncryptKey;//密匙容器的名称,保持加密解密一致才能解密成功
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
{
byte[] plaindata = Encoding.Default.GetBytes(encryptString);//将要加密的字符串转换为字节数组
byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
}
}
/**/
/// <summary>
/// 解密
/// </summary>
/// <param name="decryptString"></param>
/// <returns></returns>
public static string Decrypt(string decryptString)
{
param = new CspParameters();
param.KeyContainerName = EncryptKey;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
{
byte[] encryptdata = Convert.FromBase64String(decryptString);
byte[] decryptdata = rsa.Decrypt(encryptdata, false);
return Encoding.Default.GetString(decryptdata);
}
}
}