Search code examples
phpformssecuritytokencsrf

form security token (CSRF) - why use bin2hex in bin2hex(random_bytes(32))


I'm trying to add a token to my form to beef up the security(i.e. CSRF). All I've found so far (on stackoverflow, and many other sites) is the recommendation to use:

$_SESSION['token'] = bin2hex(random_bytes(32));

My question is straight forward, why not just use:

$_SESSION['token'] = random_bytes(32);

why convert this to a hexadecimal representation?

Thank you


Solution

  • Random bytes won't be easily passed as the token in field of your form. You need some predictable set of characters. Just random flow of bytes are almost sure to break any client encoding (utf-8, iso-8859-1, win1252, big5, etc.) the form uses.

    On the other hand, bin2hex encoded characters will always be pure ASCII string, thus they are safe in any encoding on the client.