Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce same result as CryptoJS.enc.Base64 using PHP

Tags:

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.

like image 885
Kazi Lotus Avatar asked Jun 25 '16 11:06

Kazi Lotus


1 Answers

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);

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

like image 102
Paolo Avatar answered Sep 28 '22 01:09

Paolo