Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Generating tokens for transactions

Tags:

php

token

banking

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

like image 258
Brad Turner Avatar asked Jul 23 '16 22:07

Brad Turner


3 Answers

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.

like image 108
nathan Avatar answered Nov 19 '22 16:11

nathan


You could use the following:

bin2hex(openssl_random_pseudo_bytes(8))

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

like image 24
Robert Rocha Avatar answered Nov 19 '22 16:11

Robert Rocha


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.

like image 22
John Conde Avatar answered Nov 19 '22 16:11

John Conde