【问题标题】:All hash values are identical using Microsoft SHA256使用 Microsoft SHA256 时,所有哈希值都相同
【发布时间】:2013-08-07 21:00:40
【问题描述】:

使用以下代码,无论输入如何,我总是得到相同的哈希值。任何想法为什么会这样?

    private static SHA256 sha256;
    internal static byte[] HashForCDCR(this string value)
    {
        byte[] hash;
        using (var myStream = new System.IO.MemoryStream())
        {
            using (var sw = new System.IO.StreamWriter(myStream))
            {
                sw.Write(value);
                hash = sha256.ComputeHash(myStream);
            }
        }

        return hash;
    }

【问题讨论】:

    标签: c# hash sha sha256


    【解决方案1】:

    您可能需要刷新流。为了获得最佳性能 StreamWriter 不会立即写入流。它等待其内部缓冲区填满。刷新写入器会立即刷新内部缓冲区的内容以给流加下划线。

         sw.Write(value);
         sw.Flush();
         myStream.Position = 0;
         hash = sha256.ComputeHash(myStream);
    

    【讨论】:

    • 您需要按照以下建议设置 myStream.Position = 0。我已经编辑了我的答案以反映这一点。
    【解决方案2】:

    您正在计算流中空部分的哈希值(紧跟在您使用 sw.Write 编写的内容之后的部分),因此它始终相同。

    廉价修复:sw.Flush();myStream.Position = 0;。更好的解决方法是在原始流的基础上完成写入并创建新的只读流进行加密:

    using (var myStream = new System.IO.MemoryStream())
    {
        using (var sw = new System.IO.StreamWriter(myStream))
        {
            sw.Write(value);
        }
        using (var readonlyStream = new MemoryStream(myStream.ToArray(), writable:false)
        {
           hash = sha256.ComputeHash(readonlyStream);
        }
    }
    

    【讨论】:

    • 这会给出错误“无法访问已关闭的流”。在 ComputeHash 线上。第三个 using 语句最后还需要另一个“)”。
    • @OPOSJacob 应该是新的流 - 样本已修复。
    【解决方案3】:

    我可能会使用 Alexei Levenkov 称之为“廉价修复”的解决方案。不过,我确实遇到了另一种让它发挥作用的方法,我将把它发布给未来的读者:

    var encoding = new System.Text.UTF8Encoding();
    var bytes = encoding.GetBytes(value);
    var hash = sha256.ComputeHash(bytes);
    return hash;
    

    雅各布

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2015-01-04
      • 1970-01-01
      相关资源
      最近更新 更多