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?
2. A token where the secret is a cryptographic key. Source(s): 1. A portable, user-controlled, physical device (e.g., smart card or PC card) used to store cryptographic information and possibly also perform cryptographic functions.
You can call it from the save() method of your model. It generates a candidate token using a defined function, searches the existing rows in the database for that candidate token. If it finds one, it trys again, otherwise, it returns the candidate string.
Here is the correct solution:
$token = bin2hex(openssl_random_pseudo_bytes(16)); # or in php7 $token = bin2hex(random_bytes(16));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With