random_bytes

(PHP 7, PHP 8)

random_bytesGénère des octets pseudo-aléatoire cryptographiquement sécurisé

Description

random_bytes(int $length): string

Génère une chaîne de caractères de longueur arbitraire d'octets aléatoires cryptographiques qui convient à un usage cryptographique, comme lors de la génération de sels, de clés ou de vecteurs d'initialisation.

La source des données aléatoires utilisée pour cette fonction est :

  • Sous Windows, » CryptGenRandom() sera toujours utilisé. À partir de PHP 7.2.0 c'est » CNG-API qui sera toujours utilisé à la place
  • Sous Linux, l'appel système » getrandom(2) sera utilisé si disponible.
  • Sous les autres plate-formes, /dev/urandom sera utilisé.
  • Si tout ce qui précède n'est pas disponible, alors une Exception sera émise.

Note: Bien que cette fonction ait été ajoutée en PHP 7.0, une » implementation en espace utilisateur est disponible pour PHP 5.2 jusqu'à 5.6, inclus.

Liste de paramètres

length

La longueur de la chaîne de caractères aléatoire qui doit être retourné en octets.

Valeurs de retour

Retourne une chaîne de caractères contenant le nombre demandé d'octet aléatoire cryptographiquement sécurisé.

Erreurs / Exceptions

  • Si aucune source de données aléatoires n'est trouvée, une Exception sera émise.
  • Si un paramètre invalide est fourni, une exception de type TypeError sera émise.
  • Si une longueur length invalide d'octet est fournit, une Error sera lancé.

Exemples

Exemple #1 Exemple avec random_bytes()

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

Résultat de l'exemple ci-dessus est similaire à :

string(10) "385e33f741"

Voir aussi

  • random_int() - Génère des nombres entiers pseudo-aléatoire cryptographiquement sécurisé
  • openssl_random_pseudo_bytes() - Génère une chaine pseudo-aléatoire d'octets
  • bin2hex() - Convertit des données binaires en représentation hexadécimale
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