PHP mt_srand函数
我已经编写了一段代码,可以生成伪随机字符串。 我试图通过收集用户鼠标移动的熵来改善随机性 这是我的密码:PHP mt_srand函数,php,random,Php,Random,我已经编写了一段代码,可以生成伪随机字符串。 我试图通过收集用户鼠标移动的熵来改善随机性 这是我的密码: // As described in the PHP documentation function make_seed() { list($usec, $sec) = explode(' ', microtime()); return (float) $sec + ((float) $usec * 100000); } function rand_string($entro
// As described in the PHP documentation
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
function rand_string($entropy, $length, $chars) {
mt_srand($entropy . make_seed()); // Here is the important line
$return = '';
$charlen = strlen($chars);
for ($i=0;$i<$length;$i++) {
$rand = mt_rand(0, $charlen) - 1;
$return .= substr($chars, $rand, 1);
}
return $return;
}
$entropy = '18421828841384386426948169412548'; // Mouse movements, changes everytime
echo rand_string($entropy, 20, 'abcdefghijklmnopqrstuvwxz');
//如PHP文档中所述
函数make_seed(){
列表($usec,$sec)=爆炸('',微时间());
收益(浮动)$sec+((浮动)$usec*100000);
}
函数rand_字符串($entropy、$length、$chars){
mt_srand($entropy.make_seed());//这里是重要的一行
$return='';
$charlen=strlen($chars);
对于($i=0;$i,我编写了自己的随机字符串生成器,没有使用php的rand()函数
function rs($length,$chars)
{
$hex = sha1(microtime()); //contains hexadecimal string
$return = '';
$seedLen = strlen($chars); //length of the source characters string
$posLen = strlen($hex); //length of the hex string
for($i=0;$i<$length;$i++){
$idx_hex = $i % ($posLen-1); //make sure the address is in the hex string (if $i is too big)
$pos = hexdec($hex[$idx_hex].$hex[$idx_hex+1]);
$return .= $chars[$pos % $seedLen];
}
return $return;
}
函数rs($length,$chars)
{
$hex=sha1(microtime());//包含十六进制字符串
$return='';
$seedLen=strlen($chars);//源字符串的长度
$posLen=strlen($hex);//十六进制字符串的长度
对于($i=0;$imt_srand()采用一个无符号32位整数来初始化mersenne捻线器。
:
我建议寻找底层系统收集熵/随机位的方法。
这将是在*nix机器上,或者(更容易接触但速度较慢)在windows下
根据您的需要,这也是一个不错的选择(可能与从iv创建“可读”字符串的东西结合使用).mt_rand
默认情况下是随机种子设定的,因此不需要手动种子设定,除非您有特定需要覆盖默认种子设定。此外,您是否在同一程序运行中重复重置种子设定?如果是,也没有必要,并且可以减少随机性。很好地改善随机性
说出=p@SDC我对随机函数从来没有信心,所以我想添加一个唯一的每个用户参数。我希望在不需要熵的情况下使用PHP是安全的。我会像你说的那样尝试,谢谢。@Bondye我不确定我是否理解你的评论。你是因为这不是一个改进而讽刺吗?^^@mimipc不,不是讽刺。你只是de me微笑:D如果某个函数是伪随机的。如何改进它?对,使用非伪随机。例如,我使用我的密码。谢谢你的评论,但我不明白为什么它会比默认函数更好。无论如何,这并不比只使用微时更随机,因此它根本不是随机的。
194 /* {{{ php_mt_srand
195 */
196 PHPAPI void php_mt_srand(php_uint32 seed TSRMLS_DC)
197 {
198 /* Seed the generator with a simple uint32 */
199 php_mt_initialize(seed, BG(state));
200 php_mt_reload(TSRMLS_C);
201
202 /* Seed only once */
203 BG(mt_rand_is_seeded) = 1;
204 }
205 /* }}} */