简体   繁体   中英

C# Equivalent of PHP's raw output 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);

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

Please see this image public static string MD5Hash(string input)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM