PHP Encryption is not matching with the asp.net encryption

370 views Asked by At

Here is the code of .net

public string GetMD5Hash(string name) {
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] ba = md5.ComputeHash(Encoding.UTF8.GetBytes(name));
    StringBuilder hex = new StringBuilder(ba.Length * 2);

    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
    return Convert.ToString(hex);
}

and in the php I am using the below code

class foobar {

    public function str2hex($string) {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i++)
            $hex .= (strlen(dechex(ord($string[$i]))) < 2) ? "0" . dechex(ord($string[$i])) : dechex(ord($string[$i]));       
        return $hex;
    }

    public function GetMD5($pStr) { 
        $data = mb_convert_encoding($pStr, 'UTF-16LE', 'UTF-8');
        $h = $this->str2hex(md5($data, true)); 
        return $h;
    } 
}

$foobar = new foobar;  
$nisha =$foobar->GetMD5('5698882');
echo "</br>";
echo $nisha;

but the output is not matching with the .net encryption output both are different

1

There are 1 answers

2
Rick Roy On

To generatemd5 hash of a string in php, you simply need to use the md5() function more details at http://php.net/manual/en/function.md5.php

You can use these codes to get md5 hash which will be same for both .net and php

PHP md5 hash

<?php
echo md5('abcdefghijklmnopqrstuvwxyz');
?>

Result - > c3fcd3d76192e4007dfb496cca67e13b

.NET md5 hash

public string CalculateMD5Hash(string input)

{

    // step 1, calculate MD5 hash from input

    MD5 md5 = System.Security.Cryptography.MD5.Create();

    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);

    byte[] hash = md5.ComputeHash(inputBytes);


    // step 2, convert byte array to hex string

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < hash.Length; i++)

    {

        sb.Append(hash[i].ToString(“x2”));

    }

    return sb.ToString();

}

Result - > c3fcd3d76192e4007dfb496cca67e13b