8

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

Brad Turner
  • 91
  • 1
  • 3
  • 5
  • Additionally to provided answers - you might have used `base64` since it would be shorter than `bin2hex` – zerkms Jul 24 '16 at 01:36

3 Answers3

13

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.

nathan
  • 427
  • 1
  • 3
  • 11
2

You could use the following:

bin2hex(openssl_random_pseudo_bytes(8))

Here are the docks on how to use this to your needs.

Robert
  • 10,126
  • 19
  • 78
  • 130
1

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496