59 行
1.5 KiB
PHP
59 行
1.5 KiB
PHP
<?php
|
|
/**
|
|
* 随机 Token 生成工具
|
|
*/
|
|
class TokenHelper
|
|
{
|
|
/**
|
|
* 生成随机字符串(大小写字母+数字)
|
|
*/
|
|
public static function generate($length = 32)
|
|
{
|
|
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
$token = '';
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$token .= $chars[random_int(0, strlen($chars) - 1)];
|
|
}
|
|
return $token;
|
|
}
|
|
|
|
/**
|
|
* 生成包含特殊字符的随机字符串
|
|
*/
|
|
public static function generateStrong($length = 32)
|
|
{
|
|
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=';
|
|
$token = '';
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$token .= $chars[random_int(0, strlen($chars) - 1)];
|
|
}
|
|
return $token;
|
|
}
|
|
|
|
/**
|
|
* 生成 Base64 编码的随机字符串
|
|
*/
|
|
public static function generateBase64($length = 32)
|
|
{
|
|
return base64_encode(random_bytes($length));
|
|
}
|
|
|
|
/**
|
|
* 生成十六进制随机字符串
|
|
*/
|
|
public static function generateHex($length = 32)
|
|
{
|
|
return bin2hex(random_bytes($length / 2));
|
|
}
|
|
|
|
/**
|
|
* 生成 UUID v4
|
|
*/
|
|
public static function generateUUID()
|
|
{
|
|
$data = random_bytes(16);
|
|
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
|
|
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
|
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
|
|
}
|
|
} |