.NET 9.0 的 Blazor Web App 项目中 Hash 变换(MD5、Pbkdf2) 使用备忘

一、生成 string 对应的 MD5 码

cs 复制代码
    /// <summary>
    /// 生成 string 对应的 MD5 码
    /// </summary>
    /// <param name="str">需要转换的字符串 string:用于登录认证时,str = username + 线下传递的key + DateTime.Now.Ticks.ToString() </param>
    /// <returns>转换后的 MD5 码</returns>
    public static string GetMD5FromString(string str)
    {
        byte[] data = System.Security.Cryptography.MD5.HashData(System.Text.Encoding.UTF8.GetBytes(str));
        System.Text.StringBuilder sBuilder = new();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        return sBuilder.ToString().ToUpper();
    }

二、 生成 string 对应的 Pbkdf2 码

cs 复制代码
    /// <summary>
    /// derive a 256-bit subkey (use HMACSHA256 with 100 iterations)
    /// </summary>
    /// <param name="str">需要转换的字符串 string:用于登录认证时,通常为 username</param>
    /// <param name="password">线下传递的key</param>
    /// <param name="Ticks">用于登录认证时,通常为 DateTime.Now.Ticks.ToString(),用于检测登录认证是否超时</param>
    /// <returns>转换后的 Pbkdf2 码</returns>
    public static string GetPbkdf2FromString(string str, string password, string Ticks)
    {
        string hashed = Convert.ToBase64String(Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation.Pbkdf2(
            password: password,
            salt: System.Text.Encoding.UTF8.GetBytes(str + Ticks),
            prf: Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivationPrf.HMACSHA256,
            iterationCount: 100,
            numBytesRequested: 256 / 8));

        return hashed;
    }
相关推荐
爱敲点代码的小哥9 小时前
类型转换 递归算法 编译错误 装箱和拆箱 知识点
开发语言·c#
时光追逐者10 小时前
一个 WPF 开源、免费的 SVG 图像查看控件
开源·c#·.net·wpf
江沉晚呤时10 小时前
构建智能代理的利器:深入解析 Microsoft Agent Framework
开发语言·c#
武藤一雄11 小时前
C# 中线程安全都有哪些
后端·安全·微软·c#·.net·.netcore·线程
wuguan_11 小时前
C#递推算法
算法·c#·递推算法
de之梦-御风11 小时前
【WebAPI 模拟器】.NET 8/9 + Minimal API + Swagger + DI + WPF Host
.net·wpf·web
nnsix12 小时前
【C#】HttpPost请求 - Query参数 - URL编码方法
java·javascript·c#
无风听海13 小时前
TaskFactory
服务器·开发语言·c#
世洋Blog13 小时前
Unity编辑器基础
unity·c#·编辑器·游戏引擎
钰fly13 小时前
C#索引器 接口
c#