Skip to content

Instantly share code, notes, and snippets.

@DavidMellul
Last active March 1, 2018 10:14
Show Gist options
  • Save DavidMellul/0516f037085756d9f798599cea762a1d to your computer and use it in GitHub Desktop.
Save DavidMellul/0516f037085756d9f798599cea762a1d to your computer and use it in GitHub Desktop.
<?php
// Don't even look at the code. Just remember, the token must be cryptographically secure
// See : https://medium.com/@davidmellul/broken-by-design-2-randomness-d73f0a0536ed
function RandomToken($length = 32){ // Taken from a comment on http://php.net/manual/fr/function.random-bytes.php
if(!isset($length) || intval($length) <= 8 ){
$length = 32;
}
if (function_exists('random_bytes')) {
return bin2hex(random_bytes($length));
}
if (function_exists('mcrypt_create_iv')) {
return bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
}
if (function_exists('openssl_random_pseudo_bytes')) {
return bin2hex(openssl_random_pseudo_bytes($length));
}
}
if (userCouldLogin())
storeCSRFTokenInDatabase(RandomToken());
else
showErrorMessage();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment