赞
踩
public class DEncryptHelper
{
#region Md5加密
/// <summary>
/// 获取字符串MD5加密字符串
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>MD5加密字符串</returns>
public static string GetMd5(string str)
{
var pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
return pwd;
}
#endregion
#region 可逆加密 解密
/// <summary>
/// 加密方法
/// </summary>
/// <param name="encryptionStr">需要加密字符串</param>
/// <param name="key">密钥 8位 不够补0,超出截取</param>
/// <returns>加密后的字符串</returns>
public static string Encrypt(string encryptionStr, string key)
{
key = GetKey(key);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//把字符串放到byte数组中
//原来使用的UTF8编码,我改成Unicode编码了,不行
byte[] byt = Encoding.Default.GetBytes(encryptionStr);
//建立加密对象的密钥和偏移量
//使得输入密码必须输入英文文本
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
/// <summary>
/// 解密方法 需要参数
/// </summary>
/// <param name="decryptStr">需要解密的字符串</param>
/// <param name="key">密匙</param>
/// <returns>解密后的字符串</returns>
public static string Decrypt(string decryptStr, string key)
{
key = GetKey(key);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
byte[] byt = new byte[decryptStr.Length / 2];
for (int x = 0; x < decryptStr.Length / 2; x++)
{
int i = (Convert.ToInt32(decryptStr.Substring(x * 2, 2), 16));
byt[x] = (byte)i;
}
//建立加密对象的密钥和偏移量,此值重要,不能修改
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(byt, 0, byt.Length);
cs.FlushFinalBlock();
//建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
StringBuilder ret = new StringBuilder();
var str = System.Text.Encoding.Default.GetString(ms.ToArray());
return str;
}
private static string GetKey(string key)
{
if (key.Length < 8)//补0
{
var count = 8 - key.Length;
for (int i = 0; i < count; i++)
{
key += "0";
}
}
else if (key.Length > 8)
{
key = key.Substring(0, 8);
}
return key;
}
#endregion
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。