HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Generating random and secure CSRF tokens

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomsecuregeneratingcsrfandtokens

Problem

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 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;
        }
    }

Solution

If CSRF stands for Cross Site Request Forgery, then it's hard to imagine why I should help.

In any case, simply doing a cryptographic Whirlpool hash of a user-supplied string with a random seed value should be sufficiently random for most every purpose. The rest is just obfuscation and doesn't add to security.

Context

StackExchange Code Review Q#47031, answer score: 3

Revisions (0)

No revisions yet.