【问题标题】:Verify SHA512 Hashed Password in C#在 C# 中验证 SHA512 哈希密码
【发布时间】:2019-11-28 08:08:03
【问题描述】:

我用 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);

【问题讨论】:

  • 您无法解密数据库的加密密码。您必须加密您在登录页面上获得的密码,并将其与数据库中的密码进行比较。如果两个哈希都匹配,那么它是正确的,否则不正确。
  • @KinjalParmar 请不要乱扔“加密”和“散列”,就好像它们是一样的。您进一步混淆了 OP。
  • @Nero 这是一个相当好的理解:mking.net/blog/…
  • @KinjalParmar 我按你说的做!我不想从数据库中解密密码,但我想加密从登录字段输入的密码并将其与数据库上的密码进行比较以验证它!

标签: c# hash passwords verify


【解决方案1】:

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

可以通过 Nuget 获得一个好的 BCrypt 库:https://www.nuget.org/packages/BCrypt.Net-Next/

它的用法很直接:

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

【讨论】:

  • SHA-3 对密码也不安全吗?
  • @KunalMukherjee - 看看这个benchmark,你可以看到使用普通 GPU 仍然可以计算大约 1 Giga SHA-3 / 秒。这是因为 SHA 散列被设计为快速而不是用于散列密码。这就是为什么密码哈希函数总是提供一个成本因素来控制进行一次计算所需的时间。
【解决方案2】:

这样写代码怎么样:

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

    }
}

例子:

public void UsageExample()
  {

    Console.WriteLine(SHA.GenerateSHA512String("abc"));
    //returns DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多