Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a secure and unique token to use in an online ticket service?

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)?

like image 410
Mahdi Jedari Avatar asked Sep 19 '25 05:09

Mahdi Jedari


2 Answers

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.

like image 147
Ιησούς του ναυή Avatar answered Sep 20 '25 20:09

Ιησούς του ναυή


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

like image 43
Ahmed Salameh Avatar answered Sep 20 '25 21:09

Ahmed Salameh