采用C#sha512哈希并在php中进行比较

时间:2012-09-25 22:28:24

标签: c# php passwords sha512

我已经查找并找到了代码来获取PHP sha512哈希并在C#中匹配它。我目前正在寻找一种方法来改变在C#中创建的哈希并在PHP中获得相同的结果。我们正在慢慢地从asp.net转移到PHP,需要一种方法来检查数据库中的密码。以下是用于生成哈希的C#代码。

// Create a hash from a pwd and salt using sha512
    public static string CreatePasswordHash(string _password, string _salt)
    {
        string saltAndPwd = String.Concat(_password, _salt);
        SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();

        byte[] sha512Bytes = System.Text.Encoding.Default.GetBytes(saltAndPwd);

        byte[] cryString = sha512.ComputeHash(sha512Bytes);

        string hashedPwd = string.Empty;

        for (int i = 0; i < cryString.Length; i++)
        {
            hashedPwd += cryString[i].ToString("X");
        }

        return hashedPwd;
    }

在PHP中,我试图让它匹配,但它看起来只有几个字节。

function CreatePasswordHash($_password, $_salt)
    {            
        $saltAndPwd = $_password . $_salt;            
        $hashedPwd = hash('sha512', $saltAndPwd);      
        return strtoupper($hashedPwd);
    }

当使用上面相同的盐和密码时,我得到的结果。 第一个结果来自C#,第二个结果来自PHP:

60BB73FDA3FF7A444870C6D0DBC7C6966F8D5AD632B0A02762E0283051D7C54A5F4B01571D1A5BC8C689DBC411FEB92158383A56AFC6AE6074696AF36E16    
60BB73FDA3FF7A444870C6D0DBC7C609066F8D5AD632B0A02762E0283051D7C54A5F4B001571D1A5BC8C689DBC411FEB092158383A56AFC6AE6074696AF36E16

关于为什么这些不匹配的任何想法?它是否与字节序字节顺序有关?

4 个答案:

答案 0 :(得分:6)

尝试

hashedPwd += cryString[i].ToString("X2");

编辑PHP:

function CreatePasswordHash($_password, $_salt)
{
    $saltAndPwd = $_password . $_salt;
    $hashedPwd = hash('sha512', $saltAndPwd);

    $hex_strs = str_split($hashedPwd,2);

    foreach($hex_strs as &$hex) {
        $hex = preg_replace('/^0/', '', $hex);
    }
    $hashedPwd = implode('', $hex_strs);

    return strtoupper($hashedPwd);
}

答案 1 :(得分:2)

C#打印输出不包括前导零。

替换

hashedPwd += cryString[i].ToString("X");

hashedPwd += cryString[i].ToString("X2");

答案 2 :(得分:1)

仔细检查您在C#和PHP中使用相同的字符编码。 GetBytes返回不同的结果,具体取决于编码。 System.Text.Encoding.Default取决于操作系统的本地化。

答案 3 :(得分:0)

您可以尝试open_ssl_digest

echo openssl_digest($saltAndPwd, 'sha512');

如果你有PHP&gt; = 5.3

您还可以使用hash_algos功能查看系统支持的算法。

HTH