0

I'm trying to get a hashed string in php but the code that i'm trying to replicate is in node js and i get different result although i wrote the same thing

The code in NodeJS

const crypto = require('crypto');

const base64URLEncode = (str) => {
  return str.toString('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
};

const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest();
const createChallenge = (verifier) => base64URLEncode(sha256(verifier));

const verifier = "8uZj2CcGT9QS9uAiWOsN0EziwLnkfGEHEHHhWNOgOYpqsNrp97foyz4OK3TKQ3C6vE3T0FnN6Yo3WZ5A";
const code_challenge = createChallenge(verifier);

Here code_challenge = "5FSPNres_nZsFtubL3Zl21RmmGMytjCddX9tzW_nTAA"

My code in PHP

$code_verifier = "8uZj2CcGT9QS9uAiWOsN0EziwLnkfGEHEHHhWNOgOYpqsNrp97foyz4OK3TKQ3C6vE3T0FnN6Yo3WZ5A";
$code_challenge = rtrim(strtr(base64_encode(hash('sha256',$code_verifier)), '+/', '-_'), '=');

Here $code_challenge = "ZTQ1NDhmMzZiN2FjZmU3NjZjMTZkYjliMmY3NjY1ZGI1NDY2OTg2MzMyYjYzMDlkNzU3ZjZkY2Q2ZmU3NGMwMA"

The value of code_challenge isn't the same in the two codes although it should, i can't see where i made a mistake, can someone help please

Joee4
  • 1
  • 1
  • Please include the values that you are getting in both JS and PHP. – Sammitch Nov 03 '22 at 17:30
  • 2
    In the [`hash()`](https://www.php.net/manual/en/function.hash.php) call, `true` must be passed as 3rd parameter for the results to match. By the way, the middle line can be removed, since the last line explicitly contains the `hash()` call. – Topaco Nov 03 '22 at 17:34

1 Answers1

0

The solution is that i add 'true' to hash function thanks to @Topaco

$code_verifier = "8uZj2CcGT9QS9uAiWOsN0EziwLnkfGEHEHHhWNOgOYpqsNrp97foyz4OK3TKQ3C6vE3T0FnN6Yo3WZ5A";
$code_challenge = rtrim(strtr(base64_encode(hash('sha256',$code_verifier,true)), '+/', '-_'), '=');
Joee4
  • 1
  • 1