c# - 哈希算法 SHA256,我的方法安全吗?如何添加盐值以使其更安全

标签 c# security hash cryptography sha256

我对密码学很陌生,想了解哈希算法。

我有以下来源来创建密码的哈希版本,可以存储在我的数据库中。

    public static string hashPasswordGenerator(string password)
    {
        System.Security.Cryptography.SHA256Managed crypt = new System.Security.Cryptography.SHA256Managed();
        StringBuilder hash = new StringBuilder();
        byte[] cry = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
        return Convert.ToBase64String(cry);
    }

我的示例用户是 User1,密码为 Password1,这将返回 GVE/3J2k+3KkoF62aRdUjTyQ/5TVQZ4fI2PuqJ3+4d0= 的哈希版本>/p>

我的问题是:

  1. Is this secure?
  2. Should I add a salt to this? If so can someone show me a simple example as I do not really understand how the salt it generated so that it will match the password every time?
  3. If someone has this hashPasswordGenerator method could they reverse engineer my password?

提前致谢。

最佳答案

Is this secure?

如果您只是使用不加盐的 SHA2,则并非如此。 (不是说 SHA2 可以轻易逆转)

Should I add a salt to this?

是的。

If so can someone show me a simple example

使用RNGCryptoServiceProvider :

RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
var salt = new byte[32];
rngCsp.GetBytes(salt); // this will fill the buffer with random values

as I do not really understand how the salt it generated so that it will match the password every time

您必须保存盐(每个密码必须是唯一的)以及散列(密码+盐)。

If someone has this hashPasswordGenerator method could they reverse engineer my password?

是的,如果它是字典密码并且您没有使用盐。否则不会(在可预见的 future ),因为散列应该很难逆转。

顺便说一句,与其尝试重新发明轮子,不如考虑使用 PBKDF2满足您的密码散列需求,因为它有一个可以减慢暴力攻击(迭代次数)的工作因素。

关于c# - 哈希算法 SHA256,我的方法安全吗?如何添加盐值以使其更安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37499112/

相关文章:

c# - 从 C# 启动 Java 平台

Java IntStream、Range 和 mapToDouble 以及 C# 中等效的 reduce 函数

security - Flask 文件处理 : Werkzeug Vs Flask-Uploads

php - 如何使用PHP include构建安全的环境?

php - 这个登录脚本是否良好/当前/安全?

python - Python 如何将 2 个对象视为不相等且不相同,但具有相同的 ID?

c# - 如何获得最终文件名

c# - 如何使用c#传输多个文件?

c# - 合并多个文件的 MD5 哈希值

c# - 将字符串映射到整数的哈希