random_bytes

(PHP 7, PHP 8)

random_bytesGenera bytes seudoaleatorios criptográficamente seguros

Descripción

random_bytes(int $length): string

Genera una cadena de longitud arbitraria de bytes aleatorios criptográficos aptos para usos criptográficos, como la generación de sales, claves o inicialización de vectores.

Las fuentes de aleatoriedad empleadas por esta función son las siguientes:

  • En Windows, se utilizará siempre » CryptGenRandom(). A partir de PHP 7.2.0, se usará siempre » CNG-API.
  • En Linux, se utilizará la llamada al sistema » getrandom(2) si está disponible.
  • En otras plataformas, se utilizará /dev/urandom.
  • Si no están disponibles ninguna de las fuentes citadas anteriormente, se lanzará una Exception.

Nota: Aunque esta función se añadió a PHP en PHP 7.0, hay disponible una » implementación de espacio de usuario para PHP 5.2 hasta 5.6, inclusive.

Parámetros

length

La longitud de la cadena aleatoria que debería ser devuelta en bytes.

Valores devueltos

Devuelve un string que contiene el número solicitado de bytes aleatorios criptográficamente seguros.

Errores/Excepciones

  • Si no se puede encontrar una fuente de aleatoriedad apropiada, se lanzará una Exception.
  • Si se proporcionan parámetros inválidos, se lanzará un TypeError.
  • Si se proporciona un número de bytes para length inválidos, se lanzará un Error.

Ejemplos

Ejemplo #1 Ejemplo de random_bytes()

<?php
$bytes 
random_bytes(5);
var_dump(bin2hex($bytes));
?>

El resultado del ejemplo sería algo similar a:

string(10) "385e33f741"

Ver también

add a note add a note

User Contributed Notes 7 notes

up
54
akam at akameng dot com
8 years ago
I used below function to create random token, and also a salt from the token. I used it in my application to prevent CSRF attack.

<?php
function RandomToken($length = 32){
    if(!isset(
$length) || intval($length) <= 8 ){
     
$length = 32;
    }
    if (
function_exists('random_bytes')) {
        return
bin2hex(random_bytes($length));
    }
    if (
function_exists('mcrypt_create_iv')) {
        return
bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
    }
    if (
function_exists('openssl_random_pseudo_bytes')) {
        return
bin2hex(openssl_random_pseudo_bytes($length));
    }
}

function
Salt(){
    return
substr(strtr(base64_encode(hex2bin(RandomToken(32))), '+', '.'), 0, 44);
}

echo (
RandomToken());
echo
"\n";
echo
Salt();
echo
"\n";

/*
This function is same as above but its only used for debugging
*/
function RandomTokenDebug($length = 32){
    if(!isset(
$length) || intval($length) <= 8 ){
     
$length = 32;
    }
   
$randoms = array();
    if (
function_exists('random_bytes')) {
       
$randoms['random_bytes'] = bin2hex(random_bytes($length));
    }
    if (
function_exists('mcrypt_create_iv')) {
       
$randoms['mcrypt_create_iv'] = bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
    }
    if (
function_exists('openssl_random_pseudo_bytes')) {
       
$randoms['openssl_random_pseudo_bytes'] = bin2hex(openssl_random_pseudo_bytes($length));
    }
   
    return
$randoms;
}
echo
"\n";
print_r (RandomTokenDebug());

?>
up
6
ccbsschucko at gmail dot com
5 years ago
<?php
   
function str_rand(int $length = 64){ // 64 = 32
       
$length = ($length < 4) ? 4 : $length;
        return
bin2hex(random_bytes(($length-($length%2))/2));
    }
   
   
var_dump(str_rand());
   
// d6199909d0b5fdc22c9db625e4edf0d6da2b113b21878cde19e96f4afe69e714
?>
up
0
yendrrek at gmail dot com
3 years ago
mcrypt_create_iv

Warning
This function was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0.

https://www.php.net/manual/en/function.mcrypt-create-iv.php
up
0
Anonymous
6 years ago
Simple php implementation of Blum Blum Shub.

<?php

$bbs
= new BlumBlumShub(400);
var_dump(bin2hex($bbs->getRandomPseudoBytes(32)));
// out like 02b3b55d6aea2f26a0ddfcd8967597fb0d38d7c6c4027f0595f5a614b9f06400

class BlumBlumShub
{
    private
$p, $q, $s, $m, $init, $x0;
    private
$size = 1024;

    public function
__construct($size = false, $p = false, $q = false, $s = false)
    {
        if(
$p !== false && $q !== false && $s !== false)
        {
           
$this->p = $p;
           
$this->q = $q;
           
$this->m = bcmul($p, $q);
           
$this->s = $s;
        } else {
            if(
$size !== false)
               
$this->size = $size;
           
$this->init();
        }
       
       
$this->xn = bcmod(bcmul($this->s, $this->s), $this->m);
        for(
$i=0;$i<10;$i++)
           
$this->xn = bcmod(bcmul($this->xn, $this->xn), $this->m);
    }
   
    private function
init()
    {
       
$this->p = $this->genPrime();
       
$this->q = $this->genPrime();
       
$this->m = bcmul($this->p, $this->q);
       
       
$mCoPrime = gmp_init($this->m);

       
# try find co-prime
       
while(1)
        {
           
$s = genPrime($this->size);
           
$sCoPrime = gmp_init($s);
           
$g = gmp_gcdext($mCoPrime, $sCoPrime);
           
$g = gmp_strval($g['g']);
            if(
$g === '1')
                break;
        }

       
$this->s = $s;
    }
   
    public function
genPrime()
    {
        while(
1)
        {
           
$min = gmp_init(str_pad('1', $this->size, '0'));
           
$max = gmp_init(str_pad('9', $this->size, '0'));
           
$prime = gmp_strval(gmp_random_range($min, $max));

           
$validate = bcmod($prime, '4');
            if(
$validate === '3')
                break;
        }

        return
$prime;
    }
   
    public function
getRandomPseudoBytes($length)
    {
       
$bytes = '';
   
        for(
$i=0;$i<$length;$i++)
           
$bytes .= $this->getByte();
       
        return
$bytes;
    }
   
    public function
getByte()
    {
       
$byte = '';

        for(
$i=0;$i<8;$i++) {
           
$this->xn = bcmod(bcmul($this->xn, $this->xn), $this->m);
           
$byte .= substr(decbin($this->xn[strlen($this->xn)-1]), -1);
        }
       
        return
chr(bindec($byte));
    }
}
?>
up
-3
ccb2357 at gmail dot com
3 years ago
<?php
   
// PHP >= 7
   
function str_rand(int $length = 20){
       
$ascii_codes = range(48, 57) + range(97, 122);
       
$codes_lenght = (count($ascii_codes)-1);
       
shuffle($ascii_codes);
       
$string = '';
        for(
$i = 1; $i <= $length; $i++){
           
$previous_char = $char ?? '';
           
$char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            while(
$char == $previous_char){
               
$char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            }
           
$string .= $char;
        }
        return
$string;
    }
?>
up
-33
ccb_bc at hotmail dot com
6 years ago
function str_rand($largura = 32){
        $chars = str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
        // separar a string acima com uma virgula após cada letra ou número;
        $chars = preg_replace("/([a-z0-9])/i", "$1,", $chars);
        $chars = explode(',', $chars);

        $string_generate = array();
        for($i = 0; $i < $largura; $i++){
            // $chars[random_int(0, 61) = largura da array $chars
            array_push($string_generate, $chars[random_int(0, 61)]);
        }
        $string_ready = str_shuffle(implode($string_generate));
       
        for($i = 0; $i < random_int(256,512); $i++){
            $random_string = str_shuffle($string_ready);
        }
        // se a largura for um número par o numero de caracteres da string for maior ou igual a 4
        if($largura % 2 === 0 && strlen($random_string) >= 4){
            $random_string_start = str_shuffle(substr($random_string, 0, $largura / 2));
            $random_string_end = str_shuffle(substr($random_string, $largura / 2, $largura));
            $new_random_string = str_shuffle($random_string_start . $random_string_end);
            return str_shuffle($new_random_string);
        }
        else {
            return str_shuffle($random_string);
        }
    }
up
-32
atesin () gmail ! com
6 years ago
if unavailable use this with core functions... maybe not as secure and optimized (any help?), but practical

<?php

$bytes
= '';
while (
strlen($bytes) < $lenght)
 
$bytes .= chr(mt_rand(0, 255));

?>
To Top