laravel str_Random()函数是否足够随机,以便我可以将其用于ID?

For example:

str_random(32);

这将生成一个长度为32的随机字符串,由字母数字字符[a-zA-z0-9](总共62个字符)组成.

Which equates to 2272657884496751345355241563627544170162852933518655225856 possibilities.

然而,我的问题是,这足够好吗?或者我应该考虑使用UUID或其他自定义函数.

推荐答案

str_random (Str::random()) tries to use openssl_random_pseudo_bytes which is a pseudo random number generator optimized for cryptography, not uniqueness. If openssl_random_pseudo_bytes is not available, it falls back to quickRandom():

public static function quickRandom($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}

In my opinion quickRandom code is not reliable for uniqueness nor cryptography.

是的,使用openssl_random_pseudo_bytes字节和32字节几乎不可能看到冲突,但仍然有可能.如果想确保字符串/数字是唯一的(99.99%),最好使用UUID函数.这是我通常使用的:

/**
 * 
 * Generate v4 UUID
 * 
 * Version 4 UUIDs are pseudo-random.
 */
public static function v4() 
{
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

    // 32 bits for "time_low"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff),

    // 16 bits for "time_mid"
    mt_rand(0, 0xffff),

    // 16 bits for "time_hi_and_version",
    // four most significant bits holds version number 4
    mt_rand(0, 0x0fff) | 0x4000,

    // 16 bits, 8 bits for "clk_seq_hi_res",
    // 8 bits for "clk_seq_low",
    // two most significant bits holds zero and one for variant DCE1.1
    mt_rand(0, 0x3fff) | 0x8000,

    // 48 bits for "node"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

It generates a VALID RFC 4211 COMPLIANT version 4 UUID.

Check this: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions

Laravel相关问答推荐

CKEditor在laravel中的p标记之前和之后添加额外的p标记

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

Laravel 语法 GroupBy 获取列到数组

Laravel 9 中使用 WHERE 子句的列的 SUM

在 Laravel 中清除 Routes&config:cache 后未定义的常量

Laravel 5 如何配置 Queue 数据库驱动程序以连接到非默认数据库?

Laravel 集合排序不生效

laravel 关系集合上的自定义排序

Laravel 5 Eloquent 范围连接并 Select 特定列

如何通过一个 laravel 安装处理子域

Laravel 5 - 没有重叠的任务计划不起作用

Laravel Blade 没有额外的空格?

如何仅从 laravel FormRequest 中获取经过验证的数据?

计算laravel中查询返回的行数

Laravel 迁移 - 删除列

Laravel 字符串验证以允许空字符串

将 Laravel 集合排序为 ID 数组

Laravel hasManyThrough

[Vue 警告]:找不到元素:#app

无法在控制器的构造函数上调用 Auth::user()