You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.9 KiB

using System;
using System.Security.Cryptography;
using System.Text;
namespace EC.Utils.Security
{
/// <summary>
/// 加密、解密帮助类
/// </summary>
public static class DesEncrypt
{
/// <summary>
/// 加密数据
/// </summary>
/// <param name="str">需要加密的内容</param>
/// <param name="key">秘钥</param>
/// <returns></returns>
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();
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="str">需要解密的内容</param>
/// <param name="key">秘钥</param>
/// <returns></returns>
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());
}
}
}