class DesHelper
{
/// <summary>
/// DES加密方法
/// </summary>
/// <param name="prestr">待加密的字符串</param>
/// <param name="key">加密的密码(只能为8位长)</param>
/// <param name="encoding">编码方式(默认为UTF-8)</param>
/// <returns>加密结果</returns>
public static string Encrypt(string prestr, string key, Encoding encoding = null)
{
encoding = encoding ?? Encoding.GetEncoding("UTF-8");
//注意iv的长度,必须和key中的密码长度相同
var iv = Encoding.ASCII.GetBytes(key);
var keyArray = Encoding.ASCII.GetBytes(key);
var datas = encoding.GetBytes(prestr);
var desCryptoServiceProvider = new DESCryptoServiceProvider();
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateEncryptor(iv, keyArray), CryptoStreamMode.Write))
{
cryptoStream.Write(datas, 0, datas.Length);
cryptoStream.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in memoryStream.ToArray())
{
ret.AppendFormat("{0:X2}", b);//十六进制编码
}
return ret.ToString();
}
}
}
/// <summary>
/// DES 解密方法
/// </summary>
/// <param name="prestr">待加密的字符串</param>
/// <param name="key">加密的密码(只能为8位长)</param>
/// <param name="encoding">编码方式(默认为UTF-8)</param>
/// <returns>加密之结果</returns>
public static string Decrypt(string prestr, string key, Encoding encoding = null)
{
encoding = encoding ?? Encoding.GetEncoding("UTF-8");
var iv = Encoding.ASCII.GetBytes(key);
var keyArray = Encoding.ASCII.GetBytes(key);
//把字符串放到byte数组中
byte[] datas = new byte[prestr.Length / 2];
for (int x = 0; x < prestr.Length / 2; x++)
{
int i = (Convert.ToInt32(prestr.Substring(x * 2, 2), 16));
datas[x] = (byte)i;
}
var desCryptoServiceProvider = new DESCryptoServiceProvider();
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateDecryptor(iv, keyArray), CryptoStreamMode.Write))
{
cryptoStream.Write(datas, 0, datas.Length);
cryptoStream.FlushFinalBlock();
return encoding.GetString(memoryStream.ToArray());
}
}
}
}