嗨,伙计们,我有一个代码来生成随机的唯一字符串,长度为 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));