大家好我有一个代码来生成随机的唯一字符串,长12个字符。
$random_string = sha1(uniqid(rand(10, 1000), true));
$random_string = substr($random_string , rand(0, strlen($random_string ) - 12), 12);
我的代码是否安全可用于碰撞? 对上述代码有任何建议或修改吗?
谢谢你们!
答案 0 :(得分:2)
也许你应该调查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));