简体   繁体   中英

Under what circumstances does PHP's openssl_random_pseudo_bytes return false?

The PHP documentation for openssl_random_pseudo_bytes says:

Return Values

Returns the generated string of bytes on success, or false on failure.

What would cause openssl_random_pseudo_bytes to fail? Can this be manually triggered for testing purposes? I tried disabling the entire openssl PHP extension, but as expected that raised an error due to the function not being found.

When PHP cannot quantify the integer in a manner that will encrypt the integer, it will, in fact, return false. It goes without saying, it is ASSUMED php uses whole numbers for this function.. However it appears they left room for non-whole numbers (less than 1) and negative integers.. Just in case.

For example:

<?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";
    }

}

Output:

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

Version of 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

Because PHP was not able to quantify .9 or -1 (anything less than 1), even though IT IS an integer, it will fail. Although this isn't expressly denoted in the documentation, one can assume this prevents fatal errors (division by zero and such) and presents error handling possibility for anyone who might be doing arithmetic on said integer before it's passed through the openssl_random_pseudo_bytes function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM