4

I need an approach to generate a cryptographically secure and unique token in order to use in an online ticket sale service. What issues should I consider to implement and what is the best practice in Php (Laravel)?

Mahdi Jedari
  • 712
  • 1
  • 7
  • 16

5 Answers5

2

Try this:

bin2hex(random_bytes(64));

PHP bin2hex function : https://www.php.net/manual/en/function.bin2hex.php

PHP random bytes function : https://www.php.net/manual/en/function.random-bytes.php

Ahmed Salameh
  • 269
  • 2
  • 11
2

Unique token? install paragonie/constant_time_encoding

Base64UrlSafe::encode(random_bytes(9))

  • In MySQL, an INTEGER(11) UNSIGNED primary key can hold about 4 billion rows. This is equal to 32 bits.
  • If you generate 9 raw bytes from a cryptographically secure pseudorandom number generator (72 bits of possible values), then base64 the result, you will end up with a 12 character identifier.
  • 72 bits of possible values means a 50% chance of collision at 2**36 records, according to the birthday problem.

This means you have a 50% chance of only two duplicate random values after about 69 billion records (a far cry beyond your 4 billion storage capacity). This means that you will almost never have a collision. You should still make sure every selector you generate is unique before inserting a new one, of course.

source


Note: this is just to answer the question, scroll down for more approach.

Community
  • 1
  • 1
tempra
  • 2,455
  • 1
  • 12
  • 27
1

If you are using Laravel there is a random string generator built-in

use Illuminate\Support\Str;

$random = Str::random(40);

More info https://laravel.com/docs/5.7/helpers#method-str-random

I've used something similar before, it's a little extra check to make sure that the token has not already been used before. The chances are so low that this is almost unnecessary.

$findKey = function() {
    $proposed = Str::random(40);
    if (Thing::where('token', $proposed)->count() === 0) {
        return $proposed;
    }
    $findKey();
 };
 $this->token = $findKey();
 $this->save();
squareborg
  • 1,562
  • 14
  • 18
0

Laravel build-in provide function which provide us uuid so you can use that. Here is an example of that

use Illuminate\Support\Str;

return (string) Str::uuid();

And here is the reference link

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52
0

Go for JWT Auth Token

I think it is the most secure and unique token generator I have. every time, you login to the system, it generates different tokens for one person.

JWT Auth token from https://jwt.io/introduction/

Hardik Davra
  • 29
  • 1
  • 9