In order to generate a 32 character token for access to our API we currently use:
$token = md5(uniqid(mt_rand(), true));
I have read that this method is not cryptographically secure as it’s based on the system clock, and that openssl_random_pseudo_bytes
would be a better solution as it would be harder to predict.
If this is the case, what would the equivalent code look like?
I presume something like this, but I don’t know if this is right…
$token = md5(openssl_random_pseudo_bytes(32));
Also what length makes sense that I should pass to the function?
Advertisement
Answer
Here is the correct solution:
$token = bin2hex(openssl_random_pseudo_bytes(16)); # or in php7 $token = bin2hex(random_bytes(16));