【问题标题】:Can't Turn Hashed Password Byte Array Back Into String无法将散列密码字节数组转回字符串
【发布时间】:2020-11-30 13:03:11
【问题描述】:

我正在编写一个包含注册和所有功能的身份验证系统。密码用盐散列。我遇到了一个问题,我正在使用的实现使用盐操作,最终的哈希是字节数组。我无法将其转回可以存储在 SQL 中的常规人类可读字符串,并且在打印到控制台时,我已经尝试了 Encoding 类中的几乎所有编码。

任何帮助将不胜感激。我只是错过了一些非常明显的东西吗?

下面的代码示例:

class Program
    {
        static void Main(string[] args)
        {
            //The salt and hash sizes are 16 bytes (128 bits)
            int saltSize = 16;
            int hashSize = 16; 
            int iterations = 100000;

            RNGCryptoServiceProvider randomness = new RNGCryptoServiceProvider();
            byte[] salt = new byte[saltSize];
            randomness.GetBytes(salt);

            string password = "Mypassissecure7";
            byte[] passBytes = Encoding.Default.GetBytes(password);

            Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(passBytes, salt, iterations, HashAlgorithmName.SHA512);

            byte[] hash = pbkdf2.GetBytes(hashSize);
            
        }
    }

【问题讨论】:

  • Base64 字符串有什么问题? stackoverflow.com/questions/11743160/…
  • 你说“这不正确”——凭什么?你想找回什么?
  • @RachelAmbler 我在看到您的评论之前添加了该编辑。我曾通过 Intellisense 自己尝试过这条线。我怀疑它仍然可能不正确,因为我对文本编码一无所知,而且这是在黑暗中刺伤。我现在看到你的建议感觉好多了,很可能会继续前进!谢谢。
  • 所有 Base64 编码所做的只是使用 Alpha、数字和 + 或 / 符号将二进制字符串转换为极其安全的文本字符串。
  • 我认为使用十六进制字符串作为哈希值更常见,但也取决于用例。但如果是用于 SQL,为什么不直接使用 BLOB、二进制或 varbinary 来存储 byte[]

标签: c# hash salt password-hash pbkdf2


【解决方案1】:

为了完成:

var base64String = System.Convert.ToBase64String(hash);

var hexString = BitConverter.ToString(hash);

【讨论】:

  • 注意后者 - docs.microsoft.com/en-us/dotnet/api/… - All the elements of value are converted. The order of hexadecimal strings returned by the ToString method depends on whether the computer architecture is little-endian or big-endian.。即hexString的值在不同的机器上会有所不同。
猜你喜欢
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2021-12-02
相关资源
最近更新 更多