comparison of random_bytes fails when values match

Brief but interesting one here. I probably have something odd here, but I’ve lost a few hours now and can’t find out what is the issue.

I have a function that produces a nonce, like so. It’s not very complex at the moment, but is more an experimentation of a concept that is new to me. I’m using random_bytes as the natural successor to mcrypt_create_iv for PHP7+:

$token = random_bytes(16);

this is then stored like so:


(which is essentially....)
$_SESSION[$var] = $val;

whilst simultaneously being used in my form, like so:

<input name="token" type="hidden" value="<?=$token?>">

The form submits and passes through some validation and so on. As part of this, I retrieve both values:

$token = $_POST['token'];
$nonce = $session->get('nonce');

and then I have a validation point for further execution – only proceed if the two values match. Problem is, I can’t actually get them to validate. Neither of these current output true:

if(hash_equals($nonce, $token))
if($nonce === $token)

var_dumpshows both are strings of equal length, but for some reason they aren’t comparable. Both values look like they match.

if(hash_equals($nonce, $nonce))

equals to true (as you’d expect), so I can only assume that one of the values is becoming altered along the way, either by $_POST or via my retrieval function (which literally just reads from the session).

I’d appreciate any help/suggestions with this – I’m either overlooking something obvious, or too inexperienced with this.

Source: stackoverflow-php