代码之家  ›  专栏  ›  技术社区  ›  CJ Dennis

PHP的openssl_random_pseudo_bytes在什么情况下返回false?

  •  0
  • CJ Dennis  · 技术社区  · 4 年前

    The PHP documentation for openssl_random_pseudo_bytes 说:

    返回值

    成功时返回生成的字节字符串,或 错误的 关于失败。

    会导致什么 openssl_random_pseudo_bytes 失败?这是否可以出于测试目的手动触发?我尝试禁用整个openssl PHP扩展,但正如预期的那样,由于找不到函数,这引发了一个错误。

    1 回复  |  直到 4 年前
        1
  •  0
  •   Zak    4 年前

    当PHP无法以加密整数的方式量化整数时,它实际上会返回false。不用说,这是假设 php 对此函数使用整数。。然而,它们似乎为非整数(小于1)和负整数留出了空间。。以防万一。

    例如

    <?php
    
    echo test_rando(80); // Passes
    
    echo test_rando(80.1); // Passes
    
    echo test_rando(.9);  //  Fails
    
    echo test_rando(-1);  // Faile
    
    
    function test_rando($rando_in){
    
        $rando = openssl_random_pseudo_bytes($rando_in);
    
        if ($rando === false){
            return  "\n\n$rando_in | WAS FALSE\n\n ";
        }else{
            return "\n\n$$rando_in | $rando\n\n";
        }
    
    }
    

    输出

    80 | ghg'O8I*%&E(Et(wX"vUH$0
    t|5|衖y䰆rW+;
    
    80.1 |  &iGkb s`+[byaqvgөrTE݁ᨈ\Ukfb'
    
    0.9 | WAS FALSE
    
    -1 | WAS FALSE
    

    PHP版本

    PHP 8.0.10 (cli) (built: Aug 26 2021 15:50:07) ( NTS )
    Copyright (c) The PHP Group
    Zend Engine v4.0.10, Copyright (c) Zend Technologies
        with Zend OPcache v8.0.10, Copyright (c), by Zend Technologies
    

    --

    PHP 7.0.33-0ubuntu0.16.04.16 (cli) ( NTS )
    Copyright (c) 1997-2017 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
        with Zend OPcache v7.0.33-0ubuntu0.16.04.16, Copyright (c) 1999-2017, by Zend Technologies
    

    因为PHP无法量化 .9 -1 (小于1的任何值),即使它是一个整数,它也会失败。尽管文档中没有明确指出这一点,但可以假设这可以防止致命错误(除以零等),并为可能在所述整数通过 openssl_random_pseudo_bytes 作用

    推荐文章