使用 random_bytes() 生成安全随机数,再结合 bin2hex() 或 base64_encode() 转换为字符串。避免使用 rand()、mt_rand() 或 str_shuffle(),这些函数不具备密码学安全性。

为什么不能用 rand 和 mt_rand
rand() 和 mt_rand() 是伪随机数生成器(PRNG),其内部状态可被预测。攻击者若获取部分输出,可能反推种子并重现整个序列。而 random_bytes() 调用操作系统提供的加密安全随机源(如 Linux 的 /dev/urandom 或 Windows 的 CryptGenRandom),输出不可预测且无状态泄露风险。

在 PHP 7.0+ 中,random_bytes() 是官方推荐的安全随机数接口。它返回原始二进制数据,长度由参数指定(字节数)。若需生成固定长度的十六进制字符串,可直接对结果调用 bin2hex();若需 Base64 格式,需注意 base64_encode() 会引入 +、/ 和 =,通常需配合 rtrim() 去除尾部填充或使用 URL-safe 变体。
完整实现与运行示例
以下代码定义了一个 generateSecureString() 函数,接收目标长度和编码方式('hex' 或 'base64'),返回对应格式的随机字符串。保存为 secure_random.php,通过命令行执行 php secure_random.php 即可验证输出。

<?php
function generateSecureString(int $length, string $encoding = 'hex'): string {
if ($length <= 0) {
throw new InvalidArgumentException('Length must be positive.');
}
if (!in_array($encoding, ['hex', 'base64'])) {
throw new InvalidArgumentException('Encoding must be hex or base64.');
}
if ($encoding === 'hex') {
// bin2hex outputs 2 chars per byte
$bytes = random_bytes(ceil($length / 2));
return substr(bin2hex($bytes), 0, $length);
}
// For base64, we need to estimate bytes to get close to $length
// base64 encodes 3 bytes into 4 characters
$byteLen = ceil($length * 3 / 4);
$encoded = base64_encode(random_bytes($byteLen));
// Remove padding and truncate to exact length
return rtrim(str_replace(['+', '/'], ['-', '_'], $encoded), '=')[0:$length];
}
// Example usage:
echo "Hex (16): " . generateSecureString(16, 'hex') . "\n";
echo "Base64 (16): " . generateSecureString(16, 'base64') . "\n";
运行程序将输出两行:第一行为 16 位十六进制字符串(仅含 0-9a-f),第二行为 16 位 URL-safe Base64 字符串(不含 +/=)。若修改 $length 为 32,输出长度同步变化。注意 Base64 模式中使用 - 和 _ 替代 + 和 /,以避免 URL 编码问题。
该函数先校验输入合法性,确保长度大于零且编码方式合法。随后调用 random_bytes() 获取等长或适当比例的原始字节,再根据编码方式转换。Base64 模式下,为控制输出长度接近请求值,通常按 ceil(length * 3 / 4) 估算所需字节数,并截断多余字符以保持精确长度。
base64_encode 长度偏差处理
直接使用 base64_encode(random_bytes($len)) 会导致输出长度约为输入字节的 4/3 倍,且末尾常带 = 填充符。若业务要求严格匹配指定长度(如 16 位 Token),需手动调整字节数并截断。
示例中采用 $byteLen = ceil($length * 3 / 4) 计算所需字节数,生成后截取前 $length 个字符。此方法虽不保证每个字符均匀分布(因截断引入微小偏差),但在绝大多数安全场景下可接受。若需严格均匀分布,应使用 random_int() 映射到字符集,但性能较低。对于短令牌(如 16-32 字符),截断法已足够安全且高效。