7,765
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 加密解密钥匙
/// </summary>
private static string Key = "1b3@..&A";
/// <summary>
/// 加密函数
/// </summary>
/// <param name="data">加密数据</param>
/// <returns>返回加密后数据</returns>
public static string DesEncrypt(string data)
{
string result = string.Empty;
try
{
if (string.IsNullOrEmpty(data) == false)
{
//访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);//建立加密对象的密钥和偏移量
des.IV = ASCIIEncoding.ASCII.GetBytes(Key); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法
byte[] inputbyteArray = Encoding.Default.GetBytes(data);//把字符串放到byte数组中
MemoryStream ms = new MemoryStream();//创建其支持存储区为内存的流
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
result = ret.ToString();
}
}
catch (Exception)
{
result = "";
}
return result;
}
/// <summary>
/// 解密E函数
/// </summary>
/// <param name="data">被解密的字符串</param>
/// <returns>返回被解密的字符串</returns>
public static string DesDecrypt(string data)
{
string result = string.Empty;
try
{
if (string.IsNullOrEmpty(data) == false)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputbyteArray = new byte[data.Length / 2];
for (int i = 0; i < data.Length / 2; i++)
{
int x = Convert.ToInt32(data.Substring(i * 2, 2), 16);
inputbyteArray[i] = (byte)x;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
cs.FlushFinalBlock();
result = System.Text.Encoding.Default.GetString(ms.ToArray());
}
}
catch (Exception e)
{
result = "";
}
return result;
}
来,使用这个