dongzhan0624 2016-01-24 15:19
浏览 70
已采纳

C#等效的PHP原始输出MD5?

I am attempting to implement a 'simpler' version of a (remote) WordPress login.

I have gotten so far, but I am a bit stuck when it comes to the WordPress algorithm to encrypt a password. This code snippet from 'class-phpass.php' (which WP uses to hash a password)...

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

According to PHP 5 manual -

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

"If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16."

To implement this in C#, thus far, I am using the code below, can be found here:

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');
}

As you can see, this C# version is the equivalent of the PHP version, but passing in FALSE as the second parameter. I have checked this by comparing the output of both versions.

In addition, the WordPress version passes TRUE. I am struggling to apply this change to the C# version.

What is the C# equivalent of the following PHP code?

$hash = md5($salt . $password, TRUE);
  • 写回答

1条回答 默认 最新

  • dongxi2163 2016-01-24 15:48
    关注

    raw output means actual bytes, you don't need to convert them into base16 string:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧