downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

openssl_seal> <openssl_public_encrypt
[edit] Last updated: Wed, 22 May 2013

view this page in

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytesGenera una cadena de bytes pseudo-aleatoria

Descripción

string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

Genera una cadena de bytes pseudo-aleatoria, con el número de bytes determinado por el parámetro length.

También indica si se usó un algoritmo criptográficamente fuerte para producir loa bytes pseudo-aleatorios, y hace esto mediante el parámetro opcional crypto_strong. Es raro que este parámetro sea FALSE, pero algunos sistemas pueden ser antiguos rotos.

Parámetros

length

La longitud de la cadena de bytes desada. Debe ser un entero positivo. PHP intentará asignar este parámetro a un entero no nulo para usarlo.

crypto_strong

Si se pasó en la función, mantendrá un valor booleano value que determina si el algoritmo usado fue "criptográficamente fuerte", p.ej., seguro para el uso con GPG, contraseñas, etc. TRUE si lo hizo, de otro modo FALSE

Valores devueltos

Devuelve el string de bytes generado si se tuvo éxito, o FALSE en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de openssl_random_pseudo_bytes()

<?php
for ($i = -1$i <= 4$i++) {
    
$bytes openssl_random_pseudo_bytes($i$cstrong);
    
$hex   bin2hex($bytes);

    echo 
"Longitudes: Bytes: $i y Hex: " strlen($hex) . PHP_EOL;
    
var_dump($hex);
    
var_dump($cstrong);
    echo 
PHP_EOL;
}
?>

El resultado del ejemplo sería algo similar a:

Longitudes: Bytes: -1 y Hex: 0
string(0) ""
NULL

Longitudes: Bytes: 0 y Hex: 0
string(0) ""
NULL

Longitudes: Bytes: 1 y Hex: 2
string(2) "42"
bool(true)

Longitudes: Bytes: 2 y Hex: 4
string(4) "dc6e"
bool(true)

Longitudes: Bytes: 3 y Hex: 6
string(6) "288591"
bool(true)

Longitudes: Bytes: 4 y Hex: 8
string(8) "ab86d144"
bool(true)

Ver también

  • bin2hex() - Convierte datos binarios en su representación hexadecimal
  • crypt() - Hashing de una sola vía de un string
  • mt_rand() - Genera un mejor número entero aleatorio
  • uniqid() - Generar un ID único


openssl_seal> <openssl_public_encrypt
[edit] Last updated: Wed, 22 May 2013
 
add a note add a note User Contributed Notes openssl_random_pseudo_bytes - [7 notes]
up
1
Anonymous
1 year 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
1
christophe dot weis at statec dot etat dot lu
1 year 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
2 years ago
Remember to request at very least 8 bytes of entropy, ideally 32 or 64, to avoid possible theorical bruteforce attacks.
up
1
Tyler Larson
3 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);
    }
?>
up
1
Tyler Larson
3 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
0
acatalept at gmail
2 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
-1
gorgo
3 years ago
a simple way to generate a random password is:
<?php
$password
= base64_encode(openssl_random_pseudo_bytes($length, $strong));
?>

this function generates a password with a fallback to mt_rand() if no openssl is available:
<?php
/**
 * generates a random password, uses base64: 0-9a-zA-Z/+
 * @param int [optional] $length length of password, default 24 (144 Bit)
 * @return string password
 */
function generatePassword($length = 24) {
        if(
function_exists('openssl_random_pseudo_bytes')) {
           
$password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
            if(
$strong == TRUE)
                return
substr($password, 0, $length); //base64 is about 33% longer, so we need to truncate the result
       
}
       
       
//fallback to mt_rand if php < 5.3 or no openssl available
       
$characters = '0123456789';
       
$characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
       
$charactersLength = strlen($characters)-1;
       
$password = '';

       
//select some random characters
       
for ($i = 0; $i < $length; $i++) {
           
$password .= $characters[mt_rand(0, $charactersLength)];
        }       
       
        return
$password;
}
?>

note: openssl_random_pseudo_bytes() is considerably slower than mt_rand.

 
show source | credits | sitemap | contact | advertising | mirror sites