Generating Session Tokens with PHP
Recently I needed to generate random strings to hex to act as a session token for Blow Worm. Using session tokens mean that you send the login credentials once, and then the server hands out a session token for use instead of the password for the rest of that session. In theory this is more secure than sending the password to the server every time.
The problem with generating random session tokens is that you need a secure random number generator, so that hackers can't attempt to guess the random numbers and hence guess the session tokens (that would be bad).
The way I did it (please leave a comment below if this is insecure!) is as follows:
- Generate ~128 bits of randomness using the OpenSSL function
openssl_random_pseudo_bytes()
. This randomness generator is apparently better thanrand()
andmt_rand()
. - Hash that resulting randomness with
SHA256
to ensure a constant session key length.
The PHP code I am currently using is as follows:
$sessionkey = hash("sha256", openssl_random_pseudo_bytes($session_key_length));
I thought that I would share this here since it took me a little while to look up how to do this. If anyone has a better way of doing this, I will gladly take suggestions and give full credit.