C# 相当于 PHP 的原始输出 MD5?



我正在尝试实现(远程)WordPress登录的"更简单"版本。

到目前为止,我已经做到了,但是当涉及到加密密码的WordPress算法时,我有点卡住了。这个代码片段来自"class-phpass.php"(WP用来散列密码)...

$hash = md5($salt . $password, TRUE);
do {
    $hash = md5($hash . $password, TRUE);
} while (--$count);

根据 PHP 5 手册 -

string md5 ( string $str [, bool $raw_output = false ] )

"如果可选raw_output设置为 TRUE,则 md5 摘要将以长度为 16 的原始二进制格式返回。"

为了在 C# 中实现这一点,到目前为止,我正在使用下面的代码,可以在这里找到:

public string Md5Sum(string strToEncrypt)
{
    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
    byte[] bytes = ue.GetBytes(strToEncrypt);
    // encrypt bytes
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] hashBytes = md5.ComputeHash(bytes);
    // Convert the encrypted bytes back to a string (base 16)
    string hashString = "";
    for (int i = 0; i < hashBytes.Length; i++)
    {
        hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
    }
    return hashString.PadLeft(32, '0');
}

如您所见,此 C# 版本等效于 PHP 版本,但传入 FALSE 作为第二个参数。我已经通过比较两个版本的输出来检查这一点。

此外,WordPress版本通过TRUE。我正在努力将此更改应用于 C# 版本。

以下 PHP 代码的 C# 等效项是什么?

$hash = md5($salt . $password, TRUE);

原始输出表示实际字节,您无需将它们转换为 base16 字符串:

public static byte[] Md5Sum_Raw(string strToEncrypt)
{
    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
    byte[] bytes = ue.GetBytes(strToEncrypt);
    // encrypt bytes
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    return md5.ComputeHash(bytes);
}

.PHP:

$s = md5('1234567890', true);
for ($i=0; $i < strlen($s); $i++)
    echo ord($s[$i]) . ' ';
232 7 241 252 248 45 19 47 155 176 24 202 103 56 161 159

C#:

byte[] hash = Md5Sum_Raw("1234567890");
for (int i = 0; i < hash.Length; i++)
    System.Console.Out.Write(hash[i] + " ");
System.Console.Out.WriteLine();
232 7 241 252 248 45 19 47 155 176 24 202 103 56 161 159

请看这张图片 公共静态字符串 MD5哈希(字符串输入)...

最新更新