.Net Core Md5加密整理

    xiaoxiao2022-07-12  144

    一、.Net Core中Md5使用说明

    .Net Core中自带Md5加密处理,使用方法和 .Net Framework中相同

    所在命名空间

    using System.Security.Cryptography;

     

    二、使用MD5 类

    方式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); }

     

    三、使用MD5CryptoServiceProvider 类

    /// <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("-", ""); }

    四、使用MD5 16位加密

    在32位基础上取中间16位:

    //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); }

    最新回复(0)