1

I have an issue with an API that requires me to run a BASE64 and MD5 of a string. While a JAVASCRIPT code I created works well with this API, I need it in PHP, and I get the worng answer.

While testing the issue, I came to a conclusion that the issue is with the way the base64_encode function works in PHP, differs, and that creates the problem. I am attaching a code that will demostrate it

var CryptoJS = require("crypto-js");
var testStr = 'hello world!';
console.log(String(CryptoJS.SHA256(testStr))); # outputs 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9
console.log(CryptoJS.enc.Base64.stringify( CryptoJS.SHA256(testStr) )); # outputs dQnlvaDHYtK6x/kNdYtbImP6Acy8VCq1498WO+CObKk=
<?php
$testStr = 'hello world!';
echo hash('sha256', $testStr); # outputs 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9
echo '<br />';
echo base64_encode(hash('sha256', $testStr)); # outputs NzUwOWU1YmRhMGM3NjJkMmJhYzdmOTBkNzU4YjViMjI2M2ZhMDFjY2JjNTQyYWI1ZTNkZjE2M2JlMDhlNmNhOQ==

I need the PHP code to output the same BASE64 result as the JS code. Can you please clarify what I'm doing wrong, and how can I fix it?

3
  • The first example is base-64 encoding the bytes 75, 09, e5, ... while the second is encoding the (presumably) utf-8 byte representation of the string "7509e5...". Commented Aug 26, 2019 at 15:26
  • I just confirmed, the output is the same as PHP's if instead of the CryptoJS Base 64 stringify you simply use: window.btoa( CryptoJS.SHA256(testStr) ) Commented Aug 26, 2019 at 15:27
  • 1
    Alternatively to Andrew's suggestion, if you use hash('sha256', $testStr, true) it will produce the first result for both (a smaller result). This causes the hash method to return a byte array instead of a string. Commented Aug 26, 2019 at 15:29

1 Answer 1

1

Your JavaScript code is encoding the raw binary hash but your PHP code is encoding the lowercase hexadecimal representation of the hash in whatever your default encoding is.

You want to use the raw_output argument of the hash() function (reference):

<?php
$testStr = 'hello world!';
echo base64_encode(hash('sha256', $testStr, true));
// dQnlvaDHYtK6x/kNdYtbImP6Acy8VCq1498WO+CObKk=

(Demo)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.