C# 在C中验证SHA512哈希密码#

C# 在C中验证SHA512哈希密码#,c#,hash,passwords,verify,C#,Hash,Passwords,Verify,我在C#中设计了一个注册页面,所有用户都必须输入密码,然后程序将对密码进行散列,然后使用SHA512散列方法将其保存到数据库中 现在,我想用数据库中保存的密码验证登录页面上输入的密码 下面的代码是我用来散列密码的方法 现在我如何在登录页面验证输入的密码 byte[] infos = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text); infos = new System.Security.Cryptography.SHA512Manage

我在C#中设计了一个注册页面,所有用户都必须输入密码,然后程序将对密码进行散列,然后使用SHA512散列方法将其保存到数据库中

现在,我想用数据库中保存的密码验证登录页面上输入的密码

下面的代码是我用来散列密码的方法

现在我如何在登录页面验证输入的密码

byte[] infos = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text);
infos = new System.Security.Cryptography.SHA512Managed().ComputeHash(infos);
String hash = System.Text.Encoding.ASCII.GetString(infos);

写这样的代码怎么样:

using System;
using System.Text;
using System.Security.Cryptography;
using CodeShare.Cryptography;

namespace CodeShare.Cryptography
{
    public static class SHA
    {

        public static string GenerateSHA512String(string inputString)
        {
            SHA512 sha512 = SHA512Managed.Create();
            byte[] bytes = Encoding.UTF8.GetBytes(inputString);
            byte[] hash = sha512.ComputeHash(bytes);
            return GetStringFromHash(hash);
        }

        private static string GetStringFromHash(byte[] hash)
        {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                result.Append(hash[i].ToString("X2"));
            }
            return result.ToString();
        }

    }
}

Sha*散列族不适合安全地存储密码,因为它们速度太快,而且很容易被强制使用。您应该切换到专用的密码哈希函数,如BCrypt、Argon2或PBKDF2,它们应用salt并使用密钥拉伸

通过Nuget可以获得一个好的BCrypt库:

它的用法非常直截了当:

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
string hashToStoreInDb = BCrypt.HashPassword(password);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
bool isPasswordCorrect = BCrypt.Verify(password, existingHashFromDb);

无法解密数据库的加密密码。您必须对登录页面上获得的密码进行加密,并将其与数据库中的密码进行比较。如果两个散列都匹配,那么它是正确的,否则就不正确。@KinjalParmar请不要像对待相同的内容一样随意使用“加密”和“散列”。你把OP弄得更糊涂了。@Nero这里有一个相当好的理解:@KinjalParmar我正按照你说的去做!我不想解密数据库中的密码,但我想加密登录字段中输入的密码,并将其与数据库中的密码进行比较,以验证它!SHA-3的密码也不安全吗?@KunalMukherjee-看看这个,你可以看到,使用普通GPU仍然可以计算大约1千兆SHA-3/秒。这是因为SHA哈希被设计为快速而不是用于哈希密码。这就是为什么密码散列函数总是提供一个成本因子,可以控制执行单个计算所需的时间。
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
string hashToStoreInDb = BCrypt.HashPassword(password);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
bool isPasswordCorrect = BCrypt.Verify(password, existingHashFromDb);