doushouhe7072 2012-01-12 08:18
浏览 110
已采纳

PHP Rand(),是否可以猜测序列中的下一个数字? 并产生更好的数字

If I generate a number using: $num=rand(0, 1000);, is it possible to guess what the next number will be?

Would I need to record a certain number of previously generated numbers? And how would I go about working out the next number?

Additional Information:

From random.org -

PHP Rand() imagePHP Rand() image

True random imageTrue random image

Thanks to Derobert's answer:

I used the method posted in his answer to generate the following image

openssl image OpenSSL image

I used the following code to do this:

// Requires the GD Library
header("Content-type: image/png");
$im = imagecreatetruecolor(512, 512)
    or die("Cannot Initialize new GD image stream");
$white = imagecolorallocate($im, 255, 255, 255);
for ($y=0; $y<512; $y++) {
    for ($x=0; $x<512; $x++) {
        if (random() === 1) {
            imagesetpixel($im, $x, $y, $white);
        }
    }
}       
imagepng($im);
imagedestroy($im);

function random(){
    $num = unpack('L', openssl_random_pseudo_bytes(4, $is_strong));


    if (!$is_strong) {
        echo 'error';
    }
    else{
        $lastDigit=substr($num[1], strlen($num[1])-1, 1);
        if($lastDigit<=4) return 0;
        return 1;
    }
}

Credits to Bo

展开全部

  • 写回答

3条回答 默认 最新

  • dongzhisang5342 2012-01-12 08:21
    关注

    Yes, it's possible, php's rand is apparently just using the underlying C library's rand, which is a pseudo-random number generator.

    How much output you'd need to observe depends on the exact algorithm used by the C library, which varies from platform to platform (and sometimes even version to version). The number of outputs you need to observer is probably fewer than ten.

    If your C library is particularly bad, you could try mt_rand which uses the Mersenne Twister algorithm. Note that this is still predictable.

    If you need unpredictable random numbers, then use openssl_random_pseudo_bytes and make sure crypto_strong is true afterwards. Note that it returns a binary string; to get a number you'll have to use something like unpack:

    $num = unpack('L', openssl_random_bytes(4, $is_strong));
    if (!$is_strong) {
        ... // handle error
    }
    

    Also note that will return a number between 0 and 2³²=4294967296, not 0–1000, so you'll need to deal with that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 调用代码提取小脑灰质体积
  • ¥15 时间序列影像组学特征筛选
  • ¥100 Mongodb不使用shell命令,也能查到一个数据库下的所有表名称吗
  • ¥15 可持续发展卫星微光数据怎么进行预处理
  • ¥15 如何使用 PyCharm 进行数据分析项目?(相关搜索:数据处理|数据集)
  • ¥15 笔记本电脑连不上WIFI,无法找到可用网络,设备管理器告警
  • ¥15 SpringMvc自定义Convert
  • ¥15 用python完成猜数字程序(初二学生)
  • ¥50 运行3d游戏会内存访问出错
  • ¥15 无法打开添加打印机 也装不了驱动,如何解决?
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部