MD5加密
/// <summary>
/// MD5加密
/// </summary>
/// <param name="content">要加密的内容</param>
/// <returns>返回加密后的密码</returns>
public static string EncodeMD5(string content)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.Default.GetBytes(content);//将字符编码为一个字节序列
byte[] md5data = md5.ComputeHash(data);//计算data字节数组的哈希值
md5.Clear();
string str = "";
for (int i = 0; i < md5data.Length - 1; i++)
{
str += md5data[i].ToString("x").PadLeft(2, '0');
}
return str;
}
DES加密与解密
//用指定的密钥 (Key) 和初始化向量 (IV) 创建对称数据加密标准 (DES) 加密器对象
static byte[] desKey=Encoding.UTF8.GetBytes("12345678"), iv=Encoding.UTF8.GetBytes("12345678");
/// <summary>
/// 加密
/// </summary>
/// <param name="content">要加密的内容</param>
/// <returns>密码</returns>
public static string Encode(string content)
{
//加密器
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//将加密的内容转换成字节数组
byte[] contentArray = Encoding.UTF8.GetBytes(content);
//在该流中加密
MemoryStream ms = new MemoryStream();
//加密流
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(desKey, iv), CryptoStreamMode.Write);
//加密 并写入流中
cs.Write(contentArray, 0, contentArray.Length);
//清空缓冲区
cs.FlushFinalBlock();
//加密结果
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 解密
/// </summary>
/// <param name="password">密文</param>
/// <returns>解密后的内容</returns>
public static string Decode(string password)
{
if (string.IsNullOrEmpty(password))
{
return "";
}
//解密器
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//将密码转换成字节数组 因为密码是从字符串转换成的base64string 所以该处应从base64string转换成字节数组
byte[] passwordArray = Convert.FromBase64String(password);
//在该流中解密
MemoryStream ms = new MemoryStream(passwordArray);
//解密流
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(desKey, iv), CryptoStreamMode.Read);
//流 用于读取解密流中解密的内容
StreamReader reader = new StreamReader(cs);
//解密结果
return reader.ReadToEnd();
}