问题 为什么我的PHP SHA256哈希不等同于C#SHA256Managed哈希


为什么这些不一样?

PHP:

    $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );

C#

    public static string ComputeHash(string plainText, string salt)
    {
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        SHA256Managed hash = new SHA256Managed();

        // Compute hash value of salt.
        byte[] plainHash = hash.ComputeHash(plainTextBytes);

        byte[] concat = new byte[plainHash.Length + saltBytes.Length];

        System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
        System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);

        byte[] tHashBytes = hash.ComputeHash(concat);

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(tHashBytes);

        // Return the result.
        return hashValue;
    }

5643
2017-08-30 21:24


起源

因为这个问题存在缺陷。它是 当量。只有它没有 看 一样 - sehe
可能是这样,但我添加了base64_encode(),但它们仍然没有产生相同的输出。 - Lemontongs


答案:


C#输出base64 ecoded字符串,PHP输出十六进制数字。更好的比较可能是将参数true传递给PHP的散列函数的末尾,并将结果传递给base64:

 $hash = base64_encode(
           hash('sha256', $userData['salt'] . hash('sha256', $password), true )
         );

9
2017-08-30 21:30



谢谢你的快速回复!我试过这个,他们现在更接近,他们不会产生相同的输出。还有其他想法吗? - Lemontongs
没关系,这完美无缺!谢谢! - Lemontongs
@Lemontongs你对上面的代码做了任何修改......我在php和c#中得到了不同的结果 - SHANib


因为他们不同。您的C#代码在最后以Base64编码对计算的哈希进行编码。 PHP只返回一个十六进制数字字符串。


3
2017-08-30 21:29





首先怀疑:

Encoding.UTF8.GetBytes(plainText);

C#使用UTF-8,你的PHP可能没有,但如果你使用来自US-ASCII子集的严格字母,你可能会很幸运。

第二个嫌疑人:

Convert.ToBase64String(tHashBytes);

你的PHP中没有关于Base64的东西。

由于PHP会给你一个十六进制编码的结果,你也应该在C#中切换到Hex。看到 这个答案 寻求解决方案


2
2017-08-30 21:31





好吧,我不是C#程序员,但有一件事突然出现在我身上:

// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(tHashBytes);

你是否在C#中使用64位编码最终输出?因为你不是PHP ...


0
2017-08-30 21:30





C#
string toHash = "abcdefg";
SHA256Managed hash = new SHA256Managed();
byte[] signatureData = hash.ComputeHash(new UnicodeEncoding().GetBytes(toHash));
string hashResult = System.Convert.ToBase64String(signatureData);
PHP
print base64_encode(hash("sha256",mb_convert_encoding("abcdefg","UTF-16LE"),true));

像顶级代码一样写,它们是一样的


-1
2018-03-01 09:43