ccruiの博客

ccruiの博客

.NetMd5计算

84
2022-03-13

.NetMd5计算

方法1

//32位大写
    using (var md5 = MD5.Create())
    {
        var result = md5.ComputeHash(Encoding.UTF8.GetBytes(inputValue));
        var strResult = BitConverter.ToString(result);
        string result3 = strResult.Replace("-", "");
        Console.WriteLine(result3);
    }

方法2

//32位大写
using (var md5 = MD5.Create())
{
    var data = md5.ComputeHash(Encoding.UTF8.GetBytes(inputValue));
    StringBuilder builder = new StringBuilder();
    // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 
    for (int i = 0; i < data.Length; i++)
    {
        builder.Append(data[i].ToString("X2"));
    }
    string result4 = builder.ToString();
    Console.WriteLine(result4);
}

方法3

/// <summary>
/// MD5加密字符串(32位大写)
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string source)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] bytes = Encoding.UTF8.GetBytes(source);
    string result = BitConverter.ToString(md5.ComputeHash(bytes));
    return result.Replace("-", "");
}

方法4

//16位大写
using (var md5 = MD5.Create())
{
    var data = md5.ComputeHash(Encoding.UTF8.GetBytes(inputValue));
    StringBuilder builder = new StringBuilder();
    // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 
    for (int i = 0; i < data.Length; i++)
    {
        builder.Append(data[i].ToString("X2"));
    }
    string result4 = builder.ToString().Substring(8, 16);
    Console.WriteLine(result4);
}