【问题标题】:Password hashing in UWPUWP 中的密码散列
【发布时间】:2017-02-23 12:04:16
【问题描述】:

我在 .net 框架中有以下代码。

public string GetHashedPassword(string password, string salt)
    {
        byte[] saltArray = Convert.FromBase64String(salt);
        byte[] passArray = Convert.FromBase64String(password);
        byte[] salted = new byte[saltArray.Length + passArray.Length];
        byte[] hashed = null;

        saltArray.CopyTo(salted, 0);
        passArray.CopyTo(salted, saltArray.Length);

        using (var hash = new SHA256Managed())
        {
            hashed = hash.ComputeHash(salted);
        }

        return Convert.ToBase64String(hashed);
    }

我正在尝试在 .net 核心中为 UWP 应用程序创建等效项。这是我目前所拥有的。

public string GetHashedPassword(string password, string salt)
  {
        IBuffer input = CryptographicBuffer.ConvertStringToBinary(password + salt, BinaryStringEncoding.Utf8);
        var hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
        var hash = hashAlgorithm.HashData(input);

        //return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hash);
    }

最后一行,将缓冲区转换回字符串不起作用。我得到了这个例外:

目标多字节代码页中不存在 Unicode 字符的映射。

如何将缓冲区转换回字符串?

【问题讨论】:

  • string 是 UTF-16LE,但您正在请求 BinaryStringEncoding.Utf8。我不知道,在这种情况下,语言投影实现了什么样的转换,也不知道您为什么要求以 UTF-8 开头。
  • 我不得不承认,我没有想到这一点。
  • 仅使用哈希函数是不够的,仅添加盐对提高安全性无济于事,加密哈希非常快。而是使用随机盐迭代 HMAC 约 100 毫秒的持续时间,然后将盐与哈希一起保存。使用PBKDF2(又名Rfc2898DeriveBytes)、password_hash/password_verifyBcrypt 等函数和类似函数。关键是让攻击者花费大量时间通过蛮力寻找密码。保护您的用户很重要,请使用安全的密码方法。

标签: c# hash uwp


【解决方案1】:

我假设您想要获取 base64 格式的散列密码,因为您在 .net 示例中这样做了。
为此,请更改:

CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hash);

到:

CryptographicBuffer.EncodeToBase64String(hash);

所以完整的方法是这样的:

public string GetHashedPassword(string password, string salt)
        {

            IBuffer input = CryptographicBuffer.ConvertStringToBinary(password + salt, BinaryStringEncoding.Utf8);
            var hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            var hash = hashAlgorithm.HashData(input);

            return CryptographicBuffer.EncodeToBase64String(hash);
        }

【讨论】:

  • 请注意,这是一种不安全的密码散列方法,不应使用,它会使用户面临风险。
猜你喜欢
  • 2011-02-18
  • 2019-02-15
  • 1970-01-01
  • 2012-12-10
  • 2015-08-13
  • 2012-05-30
  • 1970-01-01
  • 2011-06-23
  • 2018-01-20
相关资源
最近更新 更多