获取一个C#sha512哈希并在php中进行比较

获取一个C#sha512哈希并在php中进行比较,c#,php,passwords,sha512,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)

我查找并找到了获取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;
    }
当使用相同的盐和密码以上,这里是我得到的结果。 第一个结果来自C#,第二个结果来自PHP:

60BB73FDA3FF7A444870C6D0DBC7C6966F8D5AD632B0A02762E0283051D7C54A5F4B01571D1A5BC8C689DBC411FEB92158383A56AFC6AE6074696AF36E16    
60BB73FDA3FF7A444870C6D0DBC7C609066F8D5AD632B0A02762E0283051D7C54A5F4B001571D1A5BC8C689DBC411FEB092158383A56AFC6AE6074696AF36E16
你知道为什么这些不匹配吗?这与endian字节顺序有关吗?

您可以试试

如果您的PHP>=5.3

您还可以使用该函数查看系统中支持哪些算法

HTH

试试看

hashedPwd+=crysting[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);
}
C#打印输出不包括前导零

替换

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


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

可能是编码不匹配吗?您的C代码已损坏,并吞下了一些
0
s。但是您应该从普通的SHA-512迁移,因为它不足以进行密码散列。使用bcrypt进行足够的迭代,这可以通过编辑C来实现,我需要通过编辑php来实现。密码已经在数据库中了。这使得它可以通过编辑C来工作,我需要通过编辑php来工作。密码已经在数据库中。@user1698686如果它们已经在数据库中,可能最好正确地修复代码,并在可能的情况下为受影响的用户请求重置密码。我同意,但我不确定我是否能让CEO同意此操作过程。虽然我们可以做一些事情,但我们可以在他们每次登录时修复它。删除旧密码散列并用新密码散列替换。open_ssl_digest会产生相同的结果
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);
}
hashedPwd += cryString[i].ToString("X");
hashedPwd += cryString[i].ToString("X2");