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?
You are using the wrong function :base64_decode
is made to decode a base64 encoded string. Here your string is not base64 encoded so having a shorter string is totally normal.
To generate a random (readable) string you could either use bin2hex
or base64_encode
:
$data = random_bytes(32);
$b = base64_encode($data);
echo $b;
xROAVp/JUq4DuEGe87HYINXncOHArYzc9oeziO/TTNw=
you get the actual string but those character codes couldn't be displayed, depending on font you may see different count of them as 'normal' characters
if you want to see some letters you can follow some algorithm like this: https://3v4l.org/FTQL5
$str = random_bytes(13);
$decoded = '';
$letterRange = (ord('a')-ord('Z'));
for($i = 0; $i < strlen($str); $i++)
{
$decoded .= chr(ord($str[$i])%$letterRange + ord('a'));
}
echo $str.'|'.$decoded;
Use bin2hex php function on the result so you can see it
bin2hex(random_bytes(number of bytes)) or
base64_encode(bin2hex(random_bytes(number of bytes)))
random_bytes
doesn't return a base64-encoded value, so trying to decode one from the result won't get you very far.
As the manual suggests, if you're looking to generate a random "string", you need to run it through something like bin2hex
:
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
string(10) "385e33f741"