Search code examples
javascriptphpcryptographycryptojs

Produce same result as CryptoJS.enc.Base64 using PHP


I have a javascript function that I'm trying to convert to PHP, It uses CryptoJS library, speciafically components/enc-base64-min.js and rollups/md5.js. They can be found here.

In it is this bit of code

// Let's say str = 'hello';

var md5 = CryptoJS.MD5(str);
md5 = md5.toString(CryptoJS.enc.Base64);
// md5 outputs "XUFAKrxLKna5cZ2REBfFkg=="

I assumed the str variable is hashed using md5 then encoded to Base64, so I tried this simple code

$md5 = md5($str);
$md5 = base64_encode($md5);
// md5 outputs "MmZjMGE0MzNiMjg4MDNlNWI5NzkwNzgyZTRkNzdmMjI="

Then I tried validating both the outputs, looks like the JS output isnt even a valid Base64 string.

To understand further I tried to look for toString() parameter from W3Schools, but it doesnt make sense to me, as per the reference the parameter is supposed to be an integer (2, 8 or 16), then why is CryptoJS.enc.Base64 used instead?

My goal here isn't to produce a valid base64 encoded string using JS but rather to produce the same output using PHP.


Solution

  • php's md5() with a single parameter returns the md5 hash as a hex string.

    Instead you want the raw bytes (to be later encoded into Base64)

    This is md5() function definition from the manual:

    md5(string $str, bool $raw_output = false): string

    You you have to pass the optional parameter $raw_output too to md5()

    $md5 = md5($str, true);
    

    See the manual for full explanation...

    http://php.net/manual/it/function.md5.php