MD5加密

一般是对用户密码及一些重要信息加密,防止泄露。

 

/// <summary>
/// MD5加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <returns></returns>
public static string MD5Encrypt(string input)
{
return MD5Encrypt(input, new UTF8Encoding());
}

/// <summary>
/// MD5加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <param name="encode">字符的编码</param>
/// <returns></returns>
public static string MD5Encrypt(string input, Encoding encode)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(encode.GetBytes(input));
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < t.Length; i++)
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
return sb.ToString();
}

/// <summary>
/// MD5对文件流加密
/// </summary>
/// <param name="sr"></param>
/// <returns></returns>
public static string MD5Encrypt(Stream stream)
{
MD5 md5serv = MD5CryptoServiceProvider.Create();
byte[] buffer = md5serv.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
foreach (byte var in buffer)
sb.Append(var.ToString("x2"));
return sb.ToString();
}

/// <summary>
/// MD5加密(返回16位加密串)
/// </summary>
/// <param name="input"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string MD5Encrypt16(string input, Encoding encode)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string result = BitConverter.ToString(md5.ComputeHash(encode.GetBytes(input)), 4, 8);
result = result.Replace("-", "");
return result;
}

posted @ 2016-03-16 13:17  Zbu  阅读(248)  评论(0编辑  收藏  举报