110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace Common
{
public class DESEncrypt
{
public DESEncrypt() { }
#region 加密数据
/// <summary>
/// 加密处理
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns></returns>
public static string Encrypt(string str)
{
return Encrypt(str,"zhangyue2010");
}
/// <summary>
/// 加密处理
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <param name="key">key值</param>
/// <returns></returns>
public static string Encrypt(string str, string key)
{
//定义访问数据加密标准
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
byte[] inputArray;
inputArray = Encoding.Default.GetBytes(str);
dsp.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key,"md5").Substring(0,8));
dsp.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, dsp.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputArray,0,inputArray.Length);
cs.FlushFinalBlock();
StringBuilder sb = new StringBuilder();
foreach(byte b in ms.ToArray())
{
sb.AppendFormat("{0:X2}",b);
}
return sb.ToString();
}
#endregion
#region 解密数据
/// <summary>
/// 解密处理
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Decrypt(string str)
{
return Decrypt(str,"zhangyue2010");
}
/// <summary>
/// 解密处理
/// </summary>
/// <param name="str"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string Decrypt(string str, string key)
{
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
int len;
len = str.Length / 2;
byte[] inputArray=new byte[len];
int i, j;
for (i = 0; i < len; i++)
{
i = Convert.ToInt32(str.Substring(i*2,2),16);
inputArray[i] = (byte)i;
}
dsp.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key,"md5").Substring(0,8));
dsp.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms,dsp.CreateDecryptor(),CryptoStreamMode.Write);
cs.Write(inputArray,0,inputArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
#endregion
}
}