大家好,我有一个生成随机唯一字符串的代码,长度为 12 个字符。
$random_string = sha1(uniqid(rand(10, 1000), true));
$random_string = substr($random_string , rand(0, strlen($random_string ) - 12), 12);
我的代码上面的碰撞安全吗?对我上面的代码有什么建议或修改吗?
多谢你们!
也许你应该看看openssl_random_pseudo_bytes:
//returns 6 random bytes and in turn, bin2hex will make it a 12 characters string.
$rand = bin2hex(openssl_random_pseudo_bytes(6));
//编辑解决方法:
<?php
if(!function_exists('openssl_random_pseudo_bytes')) {
// doesn't use open ssl but you get the idea.
function openssl_random_pseudo_bytes($len) {
return file_get_contents('/dev/urandom', false, NULL, -1, $len);
}
}
$rand = bin2hex(openssl_random_pseudo_bytes(6));