using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Xml;
namespace MyQuery.Utils
{
/// <summary>
/// 加解密处理方法工具
/// by 贾世义 2009-3-5
/// </summary>
public static class EncryptHelper
{
/// <summary>
/// 获得MD5加密后的字符串(不可逆)
/// </summary>
/// <param name="password">明码</param>
/// <returns></returns>
public static string GetPassword(string password)
{
string result = "";
MD5 md5 = MD5.Create();//实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i++)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
result = result + s[i].ToString("X");
}
return result;
}
/// <summary>
/// 获得Des加密后字符串
/// </summary>
/// <param name="data">待加密字符</param>
/// <param name="keyCode1">密钥</param>
/// <param name="keyCode2">密钥</param>
/// <returns></returns>
public static string DesEncode(string data, string keyCode1, string keyCode2)
{
byte[] byKey = GetKey(keyCode1);
byte[] byIV = GetKey(keyCode2);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// 获得Des解密后字符串
/// </summary>
/// <param name="data">待解密字符串</param>
/// <param name="keyCode1">密钥</param>
/// <param name="keyCode2">密钥</param>
/// <returns></returns>
public static string DesDecode(string data, string keyCode1, string keyCode2)
{
byte[] byKey = GetKey(keyCode1);
byte[] byIV = GetKey(keyCode2);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
}
}
欢迎访问:http://121.18.78.216 适易查询分析、工作流、内容管理及项目管理演示平台