Laravel str_random() or custom function?

后端 未结 4 1679
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 17:26

Is the Laravel str_random() function random enough so that I can use it for IDs?

For example:

str_random(32);

This produces a rando

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 18:01

    The accepted answer was true in April of 2014 it is not accurate anymore. In November of 2014 there was a commit which removed the use of quickRandom. And as random_bytes became available in PHP 7 Laravel slowly shifted to use that function and uses only that without any fallback.

    The default UUID library in Laravel is ramsey/uuid. By looking at the code we can find out the default random generator is RandomBytesGenerator which uses random_bytes the same method what Str::random uses.

    The Wikipedia page about UUID states the following about UUID v4:

    [...] version-4 UUID will have 6 predetermined variant and version bits, leaving 122 bits for the randomly generated part, [...]

    https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)

    128 bits = 122 random bits + 6 version bits. 128 bits is exactly 16 bytes. Most of the UUID implementations reads 16 bytes of random bytes and then replaces the version at the specified position (in case of v4).

    All in all, as of now it almost the same if you would use Str::random with length equal to 16 or Uuid::uuid4 (without any modifying the randomGenerator of Uuid).

提交回复
热议问题