Question

Friends my php 5.2 codes am keeping my password like this

echo '<br>'.base64_encode(mhash(MHASH_MD5,'test'));
result  CY9rzUYh03PK3k6DJie09g==

In php 5.3 mhash extension is obsoleted by Hash like I saw in there documentation. So I tried like this. But its giving wrong result.

echo '<br>'.base64_encode(hash(MD5,'test'));
result MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=

Please help me to convert my 5.2 mhash codes to 5.3.

Thanks

Was it helpful?

Solution

Actually, they are the same, only in a different format. The first one is binary data, while the second one is hexadecimal. You can convert the first one to the second using this function:

$second_hash = bin2hex ($first_hash);

Or the other way around:

$first_hash = hex2bin ($second_hash);

Update

Add this function:

define('HEX2BIN_WS', " \t\n\r");

function hex2bin($hex_string) {
    $pos = 0;
    $result = '';
    while ($pos < strlen($hex_string)) {
      if (strpos(HEX2BIN_WS, $hex_string{$pos}) !== FALSE) {
        $pos++;
      } else {
        $code = hexdec(substr($hex_string, $pos, 2));
        $pos = $pos + 2;
        $result .= chr($code); 
      }
    }
    return $result;
}

OTHER TIPS

If you want to update obsolete mhash() method to hash_hmac() method using sha1, simply replace :

mhash(MHASH_SHA1, $data, $key)

into

hash_hmac('sha1', $data,$key,true)

In my context i was faced to old piece of code

base64_encode(mhash(MHASH_SHA1, $data, $key));

which i replaced by

base64_encode(hash_hmac('sha1', $data,$key,true));

I hope it could help.

mhash(MHASH_MD5, 'FOOBAR'); // what you have
pack('H*', hash(MD5, 'FOOBAR')) // what you accepted
pack('H*', md5('FOOBAR')); // ...
md5('FOOBAR', true); // what you could/should have used

I know this question is rather old but today I had the same problem. Based on this post I was able to find a shorter and I guess more performant way which is worth sharing in my opinion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top