Kazi Lotus Kazi Lotus - 3 months ago 15x
PHP Question

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

. 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
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
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
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.


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

Instead you want the raw bytes to be encoded into Base64 so you have to pass the optional parameter $raw_output too to md5() (set to true)

$md5 = md5($str, true);