using System;
using System.Security.Cryptography;
using System.Text;
namespace EC.Utils.Security
{
///
/// 加密、解密帮助类
///
public static class DesEncrypt
{
///
/// 加密数据
///
/// 需要加密的内容
/// 秘钥
///
public static string Encrypt(string str, string key)
{
var des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
var ms = new System.IO.MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
var byteArray = Encoding.Default.GetBytes(str);
cs.Write(byteArray, 0, byteArray.Length);
cs.FlushFinalBlock();
var builder = new StringBuilder();
foreach (var b in ms.ToArray())
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
///
/// 解密数据
///
/// 需要解密的内容
/// 秘钥
///
public static string Decrypt(string str, string key)
{
var byteArray = new byte[str.Length / 2];
for (var i = 0; i < byteArray.Length; i++)
{
byteArray[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16);
}
var des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
var ms = new System.IO.MemoryStream();
var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(byteArray, 0, byteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
}
}