Reputation: 13749
My goal is simply to generate a temporary token that will be used in URLs for user identification, should I use OAuthProvider::generateToken
or random_bytes
?
From these answers :
Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes?
and
best practice to generate random token for forgot password
It seems that random_bytes
is a more recently updated option for PHP 7 when compared to openssl_random_pseudo_bytes
. Is it the same when compared to OAuthProvider::generateToken
?
Examples:
$rb_token = bin2hex(random_bytes($length));
$oa_token = bin2hex((new OAuthProvider())->generateToken($length, TRUE));
// TRUE = strong "/dev/random will be used for entropy"
Upvotes: 3
Views: 888
Reputation: 1587
I would go for random_bytes
(if you use PHP < 7, a polyfill with a good reputations exists, random_compat).
Differences in between /dev/urandom
and /dev/random
are negligible for your case (a more detailed explanation can be found there).
random_bytes
use getrandom
syscall or /dev/urandom
, (source code), while OAuthProvider::generateToken()
without strong mode seems to fallback to some unsecure implementation if the generated string is too short (source code, and source code of php_mt_rand
). So random_bytes
has a edge over usability (no unsafe mode), and on systems using getrandom
syscall, as it should be the preferred method (detailled explanation here).
Another way to conclude is to look at some widely-used libraries: FOSOAuthServer bundle, for Symfony applications, uses random_bytes
too.
Last but not least, I believe some PHP core function will also receive more scrutinity, and better support, than an extension.
Upvotes: 3