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)?
-
you can use the unix timestamp. – zahid hasan emon Sep 14 '19 at 09:39
-
You can get help from this https://stackoverflow.com/a/26163679/1483629 – Vinay Patil Sep 14 '19 at 09:42
-
1@zahidhasanemon You mean the unix timestamp that increments by one each iteration. It's the least cryptographic system you could choose – squareborg Sep 14 '19 at 09:57
-
What do you mean by "cryptographically secure"? What are you trying to prevent an attacker from doing? – President James K. Polk Sep 14 '19 at 12:21
5 Answers
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

- 269
- 2
- 11
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.
Note: this is just to answer the question, scroll down for more approach.
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();

- 1,562
- 14
- 18
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

- 5,536
- 5
- 27
- 52
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/

- 29
- 1
- 9