Brad Turner
Brad Turner

Reputation: 91

PHP - Generating tokens for transactions

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

Upvotes: 8

Views: 26536

Answers (4)

Diwaw DW
Diwaw DW

Reputation: 1

private static function generateToken($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $token .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $token;
}

Upvotes: 0

nathan
nathan

Reputation: 451

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.

Upvotes: 16

Robert
Robert

Reputation: 10390

You could use the following:

bin2hex(openssl_random_pseudo_bytes(8))

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

Upvotes: 2

John Conde
John Conde

Reputation: 219874

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.

Upvotes: 1

Related Questions