首页 > 解决方案 > C# 哈希算法无法正常工作

问题描述

我的用户模型和数据库中有密码哈希和密码盐供注册。我正在向我的 API 发布电子邮件和密码。我正在通过电子邮件从数据库中获取用户,并且正在对来自 API 的密码进行哈希处理。此外,我相互比较,但它不能正常工作

我经常这样工作,但我从来没有遇到过麻烦,我将我的操作系统升级到了 Windows 11。我不知道,也许是 Windows 11 的原因。

 public class HashingHelper
    {
        public static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
            }
        }

        public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return false;
                    }
                }
                return true;
            }
        }
    }

CreatePasswordHash方法是在注册之前对密码进行哈希处理。 VerifyPasswordHash方法是比较来自 API 的密码和来自我的数据库的密码

标签: c#asp.nethash

解决方案


推荐阅读