php mt_rand 的缺陷

https://www.lynahex.com/index.php/archives/Cracking-Random-Number-Generator2.html

    <CodeIssue>
        <Priority>3</Priority>
        <Severity>Medium</Severity>
        <Title>mt_rand</Title>
        <Description>The application uses pseudo-random number generation that is not cryptographically secure. Carry
            out a manual check to ensure this is not being used in a process that requires cryptographically secure
            random numbers.
        </Description>
        <FileName>\WWW\user.php</FileName>
        <Line>881</Line>
        <CodeLine>$smarty->assign('rand', mt_rand());</CodeLine>
        <Checked>False</Checked>
        <CheckColour>LawnGreen</CheckColour>
    </CodeIssue>

[PHP]利用openssl_random_pseudo_bytes和base64_encode函数来生成随机字符串

openssl_random_pseudo_bytes函数本身是用来生成指定个数的随机字节,因此在使用它来生成随机字符串时,还需要配合使用函数base64_encode。如下所示:

public static function getRandomString($length = 42)
    {
        /*
         * Use OpenSSL (if available)
         */
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes($length * 2);

            if ($bytes === false)
                throw new RuntimeException('Unable to generate a random string');

            return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
        }

        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在调用base64_encode函数之后,还对结果进行了一次替换操作,目的是要去除随机生成的字符串中不需要的字符。

当然,在使用openssl_random_pseudo_bytes函数之前,最好使用function_exists来确保该函数在运行时是可用的。如果不可用,则使用Plan B:

substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
 
 
  • 1

这个函数的通用性很强,可以根据业务的需要进行适当修改然后当作静态方法进行调用。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值