PHP 5.4.31 Released

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytesYarı-rasgele dizge üretir

Açıklama

bool openssl_random_pseudo_bytes ( string $uzunluk , string $güçlü )

uzunluk karakterlik bir dizge döndürür. Ayrıca, ikinci değiştirgede bu yarı rasgele baytları üretmek için güçlü bir algoritma kullanılıp kullanılmadığı da belirtilecektir.

Değiştirgeler

uzunluk

İstenen dizgenin uzunluğu. Pozitif bir tamsayı olmalıdır. PHP, bu değiştirgeden bir pozitif tamsayı elde etmek için gerekli tür dönüşümünü yapacaktır.

güçlü

Güçlü bir algoritma kullanılmışsa bu değiştirgede TRUE döner. Bir hata oluşursa bu değer NULL olacaktır.

Dönen Değerler

İşlem başarılı olursa üretilen dizge, yoksa FALSE döner.

Örnekler

Örnek 1 - openssl_random_pseudo_bytes() örneği

<?php
for ($i = -1$i 5$i++) {
    
var_dump(bin2hex(openssl_random_pseudo_bytes($i$guclu)));
    
var_dump($guclu);
}

?>

Yukarıdaki örnek şuna benzer bir çıktı üretir:

string(0) ""
NULL
string(0) ""
NULL
string(2) "f6"
bool(true)
string(4) "8999"
bool(true)
string(6) "c202c9"
bool(true)
string(8) "45261b8f"
bool(true)

add a note add a note

User Contributed Notes 7 notes

up
11
nahun@telemako
10 months ago
Here's an example to show the distribution of random numbers as an image. Credit to Hayley Watson at the mt_rand page for the original comparison between rand and mt_rand.

rand is red, mt_rand is green and openssl_random_pseudo_bytes is blue.

NOTE: This is only a basic representation of the distribution of the data. Has nothing to do with the strength of the algorithms or their reliability.

<?php
header
("Content-type: image/png");
$sizex=800;
$sizey=800;

$img = imagecreatetruecolor(3 * $sizex,$sizey);
$r = imagecolorallocate($img,255, 0, 0);
$g = imagecolorallocate($img,0, 255, 0);
$b = imagecolorallocate($img,0, 0, 255);
imagefilledrectangle($img, 0, 0, 3 * $sizex, $sizey, imagecolorallocate($img, 255, 255, 255));

$p = 0;
for(
$i=0; $i < 100000; $i++) {
   
$np = rand(0,$sizex);
   
imagesetpixel($img, $p, $np, $r);
   
$p = $np;
}

$p = 0;
for(
$i=0; $i < 100000; $i++) {
   
$np = mt_rand(0,$sizex);
   
imagesetpixel($img, $p + $sizex, $np, $g);
   
$p = $np;
}

$p = 0;
for(
$i=0; $i < 100000; $i++) {
   
$np = floor($sizex*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
   
imagesetpixel($img, $p + (2*$sizex), $np, $b);
   
$p = $np;
}

imagepng($img);
imagedestroy($img);
?>
up
5
Tyler Larson
4 years ago
If you don't have this function but you do have OpenSSL installed, you can always fake it:

<?php
   
function openssl_random_pseudo_bytes($length) {
       
$length_n = (int) $length; // shell injection is no fun
       
$handle = popen("/usr/bin/openssl rand $length_n", "r");
       
$data = stream_get_contents($handle);
       
pclose($handle);
        return
$data;
    }
?>
up
4
Anonymous
2 years ago
Another way to get random 32bit ints:
function myRand($max){
    do{
        $result = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
    }while($result == $max);
    return $result;
}
up
2
acatalept at gmail
3 years ago
FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable.  It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it's a known problem with OpenSSL (not PHP specifically).

See: http://www.google.com/search?q=openssl_random_pseudo_bytes+slow
up
2
christophe dot weis at statec dot etat dot lu
3 years ago
Another replacement for rand() using OpenSSL.

Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.

A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.

<?php
function crypto_rand_secure($min, $max) {
       
$range = $max - $min;
        if (
$range == 0) return $min; // not so random...
       
$log = log($range, 2);
       
$bytes = (int) ($log / 8) + 1; // length in bytes
       
$bits = (int) $log + 1; // length in bits
       
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
       
do {
           
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
           
$rnd = $rnd & $filter; // discard irrelevant bits
       
} while ($rnd >= $range);
        return
$min + $rnd;
}
?>
up
1
crrodriguez at opensuse dot org
3 years ago
Remember to request at very least 8 bytes of entropy, ideally 32 or 64, to avoid possible theorical bruteforce attacks.
up
-4
Tyler Larson
4 years ago
Here's a drop-in replacement for rand() using OpenSSL as your PRNG:

<?php
   
function crypto_rand($min,$max) {
       
$range = $max - $min;
        if (
$range == 0) return $min; // not so random...
       
$length = (int) (log($range,2) / 8) + 1;
        return
$min + (hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s))) % $range);
    }
?>
To Top