32 lines
716 B
PHP
32 lines
716 B
PHP
<?php
|
||
|
||
namespace App\Service\ServiceTrait\Common;
|
||
|
||
use Random\RandomException;
|
||
|
||
trait UserTrait
|
||
{
|
||
/**
|
||
* @param int $userId
|
||
* @return string
|
||
* @throws RandomException
|
||
*/
|
||
protected function generateStableCode(int $userId): string
|
||
{
|
||
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||
$seed = $userId . random_bytes(16) . microtime(true);
|
||
|
||
// 使用分段处理避免大数
|
||
$hash = hash('sha256', $seed, true);
|
||
$code = '';
|
||
|
||
for ($i=0; $i<8; $i++) {
|
||
// 每次取1字节数据(0-255)
|
||
$byte = ord($hash[$i]);
|
||
$code .= $chars[$byte % 62];
|
||
}
|
||
|
||
return $code;
|
||
}
|
||
|
||
} |