C# MD5加密字符串

时间:2022-07-10 04:34:31
/// <summary>
/// 用MD5加密字符串,可选择生成16位或者32位的加密字符串
/// </summary>
/// <param name="password">待加密的字符串</param>
/// <param name="bit">位数,一般取值16 或 32</param>
/// <returns>返回的加密后的字符串</returns>
public string MD5Encrypt(string password, int bit)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedDataBytes;
hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(password));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("x2"));
}
if (bit == )
return tmp.ToString().Substring(, );
else
if (bit == ) return tmp.ToString();//默认情况
else return string.Empty;
}
/// <summary>
/// 用MD5加密字符串
/// </summary>
/// <param name="password">待加密的字符串</param>
/// <returns></returns>
public string MD5Encrypt(string password)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedDataBytes;
hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(password));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("x2"));
}
return tmp.ToString();
}

命名空间:System.Security.Cryptography.MD5CryptoServiceProvider