c.k c.k - 1 month ago 13
PHP Question

Alternative for openssl_random_pseudo_bytes - generate secured unique tokens

My server host had php version 5.2.17. I am using a random token and used openssl_random_pseudo_bytes in my function.

openssl_random_pseudo_bytes( $length);


Trying to run this code from Scott's answer.

It is running well on my localhost with higher php version.
Other than upgrading my server php version. What is an alternative function for
openssl_random_pseudo_bytes
?

Update: Using
mt_rand, rand or uniqid
, how can I generate secure unique tokens?
As of now, I am using this line of code:

$token = md5(uniqid(rand(), true));


$thetoken = $token.$user_id;


Thank you for any help!

Answer

I am using 5.6 but have also been looking for ways to create secure and unique tokens as I am unable to get the openssl_random_pseudo_bytes function to work. I have run across paragonie's random_compat at github which should allow you to use random_bytes() and random_int() (both only available with PHP7). They do say it should be able to be used with older 5.x versions of PHP in theory, though they do suggest updating to a current stable version of php. https://github.com/paragonie/random_compat

Here is a link to another stack overflow answer that suggests using random_bytes() as $token = bin2hex(random_bytes($length));

best practice to generate random token for forgot password

And also the link i found suggesting paragonie's random_compat https://akrabat.com/random_bytes-in-php-5-6-and-5-5/ https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php

Comments