# Generating random and secure CSRF tokens

I googled around for secure random number generation and random string generation, combining them with some user data.

Is this good or am I totally off-base? I don't know much about cryptography but I do not see many alternatives, other than some bad code that gets copied around a lot with mt_rand and uniqid.

//csrf tokens
public function csrf_token($regen = false) { if($regen === true) {
//we need to give the user a token
if(isset($_SESSION["__csrf_token"])) { unset($_SESSION["__csrf_token"]);
}
$max = mt_rand(0, mt_getrandmax());$rand_num = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));$rand_string = "";
for($i=0;$i < 11; $i++) {$x = mt_rand(0, 2);
switch($x) { case 0:$rand_string.= chr(mt_rand(97,122));break;
case 1: $rand_string.= chr(mt_rand(65,90));break; case 2:$rand_string.= chr(mt_rand(48,57));break;
}
}

$_SESSION["__csrf_token"] = hash('whirlpool',$rand_num . $this->username .$rand_string . $this->hash_pw);$this->csrf_token = $_SESSION["__csrf_token"]; return$this->csrf_token;
}else{
//the user already has a token
return \$this->csrf_token;
}
}

• To me, it looks like it's doing too much. I'd just generate 16 random bytes, convert them to hex, and be done with it. – icktoofay Apr 13 '14 at 1:06
• thanks icktoofay. you're probably right. i will consider this when refactoring the code. thank you for your time. – r3wt Apr 13 '14 at 1:34