Question

really new to Symfony 2 here. I am trying to implement the secureRandom class and nextType(int) to generate a 32 char random string. However, the method appears to be returning non standard characters (UTF8).

Code:

use Symfony\Component\Security\Core\Util\SecureRandom;

$generator = new SecureRandom();
$random = $generator->nextBytes(32);

...

Result:

#ïŽ+cÐÁ-ˆ5FZ{CD:­ïN2¨x…3ß,î2

Is there a way to specify I only want standard english chars? Thank you in advance!

Was it helpful?

Solution

Looking through the source code https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Util/SecureRandom.php it seems that by default this function tries to use the openssl function openssl_random_pseudo_bytes to generate the bytes. So to get the hex version of this you can call bin2hex.

use Symfony\Component\Security\Core\Util\SecureRandom;

$generator = new SecureRandom();
$random = $generator->nextBytes(32);
$humanReadableString = bin2hex($random);

Or save a variable assignment and translate it in 1 step:

$random = bin2hex($generator->nextBytes(32));

Each Byte is made up of 8 bits. AKA 0 or 1(binary, base 2).

Every 4 bits can be represented by 1 hex value(base 16).

So if you ask for 1 Byte(8 chars) say "11101001" then converting that to hex will give you "E9"(2 chars).

In order to use nextBytes to get a random 32 char string you will need 16 Bytes of data converted to hex values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top