note 118932 added to function.random-bytes
| From: | akam at akameng dot com | Date: | Tue, 01 Mar 2016 13:53:42 +0000 |
| Subject: | note 118932 added to function.random-bytes | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205077@lists.php.net to get a copy of this message | ||
I used below function to create random token, and also a salt from the token. I used it in my
application to prevent CSRF attack.
<?php
function RandomToken($length = 32){
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));
}
}
function Salt(){
return substr(strtr(base64_encode(hex2bin(RandomToken(32))), '+', '.'), 0,
44);
}
echo (RandomToken());
echo "\n";
echo Salt();
echo "\n";
/*
This function is same as above but its only used for debugging
*/
function RandomTokenDebug($length = 32){
if(!isset($length) || intval($length) <= 8 ){
$length = 32;
}
$randoms = array();
if (function_exists('random_bytes')) {
$randoms['random_bytes'] = bin2hex(random_bytes($length));
}
if (function_exists('mcrypt_create_iv')) {
$randoms['mcrypt_create_iv'] = bin2hex(mcrypt_create_iv($length,
MCRYPT_DEV_URANDOM));
}
if (function_exists('openssl_random_pseudo_bytes')) {
$randoms['openssl_random_pseudo_bytes'] =
bin2hex(openssl_random_pseudo_bytes($length));
}
return $randoms;
}
echo "\n";
print_r (RandomTokenDebug());
?>
----
Server IP: 72.52.91.14
Probable Submitter: 93.174.93.26
----
Manual Page -- http://php.net/manual/en/function.random-bytes.php
Edit -- https://master.php.net/note/edit/118932
Del: integrated -- https://master.php.net/note/delete/118932/integrated
Del: useless -- https://master.php.net/note/delete/118932/useless
Del: bad code -- https://master.php.net/note/delete/118932/bad+code
Del: spam -- https://master.php.net/note/delete/118932/spam
Del: non-english -- https://master.php.net/note/delete/118932/non-english
Del: in docs -- https://master.php.net/note/delete/118932/in+docs
Del: other reasons-- https://master.php.net/note/delete/118932
Reject -- https://master.php.net/note/reject/118932
Search -- https://master.php.net/manage/user-notes.php