PHP - Generating tokens for transactions
Asked Answered
S

4

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

Stertorous answered 23/7, 2016 at 22:19 Comment(1)
Additionally to provided answers - you might have used base64 since it would be shorter than bin2hexOvariotomy
A
16

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.

Alpenhorn answered 23/7, 2016 at 22:38 Comment(0)
A
2

You could use the following:

bin2hex(openssl_random_pseudo_bytes(8))

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

Amused answered 23/7, 2016 at 22:39 Comment(0)
M
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.

Monotone answered 23/7, 2016 at 22:30 Comment(1)
Thanks, I have came across random_bytes() as i'm using PHP 7.Stertorous
C
0
private static function generateToken($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $token .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $token;
}
Ching answered 28/2 at 9:39 Comment(1)
This function doesn't provide a safe implementation. Better use a more secure approach such as the random_bytes() function.Krefetz

© 2022 - 2024 — McMap. All rights reserved.