I need to generate one time use only and unique like Stripe tokens for a banking application (production only) to represent accounts and transactions, what would be a secure and appropriate method of doing this?
Could I use random_bytes()
?
It would be preferable if the tokens were alphanumeric and not just numbers.
For example, Stripe tokens look like tok_382r1O2IZ7IgsfwNFATX4xax
You can use the function bin2hex to convert the bytes to a base 62 string.
$token = bin2hex(random_bytes(16)); //generates a crypto-secure 32 characters long
You can easily prefix this by just appending a string to the beginning.
You could use the following:
bin2hex(openssl_random_pseudo_bytes(8))
Here are the docks on how to use this to your needs.
If you are using PHP 7 the new random_bytes()
function is a secure random number/string generator and is the recommended way to do this ion PHP.
If you haven't migrated to PHP 7 yet there is a compatible alternative for PHP 5 at Github called random_compat.
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