Search code examples
phpencryption

How to decode the return value of random_bytes() in PHP


I'm using random_bytes() to create a nonce which will return something like

��;w ���%N�:0���c1x*#�M��

Then when I base64_decode() it'll return something like ��� which is confusing because it's just a shorter version of something encrypted.
How do I get the actual string?


Solution

  • You are using base64_decode which is made to decode a base64 encoded string, but here your string is not base64 encoded.

    To generate a random string with readable characters you could either use bin2hex or base64_encode:

    $data = random_bytes(32);
    $b = base64_encode($data);
    echo $b;
    xROAVp/JUq4DuEGe87HYINXncOHArYzc9oeziO/TTNw=