在 C# 中重新创建 pythons werkzeug.security generate_password_hash

recreating pythons werkzeug.security generate_password_hash in C#

看起来很简单,并且有很多示例,但我似乎无法获得用 python 中的 check_password_hash 验证的散列。

    private string Generate_Passwd_Hash()
    {
        string _password = "Password";
        string _salt = "cXoZSGKkuGWIbVdr";
        SHA256 MyHash = SHA256.Create();
        byte[] hashable = System.Text.Encoding.UTF8.GetBytes(_salt + _password);
        byte[] resulthash = MyHash.ComputeHash(hashable);

        return "sha256$" + _salt + "$" + BitConverter.ToString(resulthash).Replace("-", "").ToLower();
    }

这应该生成;
sha256$cXoZSGKkuGWIbVdr$7f5d63e849f0a2c0c5c2bd6ae4e45ead2ac730c853a1ed3460e227c06c567f49
但没有。

编辑
阅读 generate_password_hash 的 python 代码,它的默认迭代次数为 260000。这可能是我所缺少的。

我从未使用过 werkzeug 但我试图重现您的问题。 我已经阅读了 werkzeug.security.generate_password_hash 的文档并意识到它仅用于密码验证,并且 并不意味着成为通用哈希算法

文件上写的很清楚

Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that check_password_hash() can check the hash.

hashlib.pbkdf2_hmacwerkzeug内部使用的散列算法(以后我们称它为底层算法)。你不需要安装它,因为它在标准库中。

check_password_hashsource code 显示它在调用基础算法之前生成随机盐。盐是为了防止攻击。 werkzeug 框架会记住它,以便 check_password_hash 以后可以用来验证。

总结一下: werkzeug.security.generate_password_hash 只保证生成的哈希可以被 check_password_hash 验证,仅此而已。您根本不能(或不应该)尝试通过其他库或语言生成相同的哈希值。

如果你真的想比较 python 和 C# 中的哈希算法,请 post 另一个问题(或更新这个问题)来比较底层算法(hashlib.pbkdf2_hmac 允许指定salt 作为参数)与 C# 版本。请注意,在 C# 中似乎没有 pbkdf2 的内置算法,请参阅 Hash Password in C#? Bcrypt/PBKDF2