random_bytes

(PHP 7)

random_bytesGenerates cryptographically secure pseudo-random bytes

Descrierea

random_bytes ( int $length ) : string

Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

Sursele de valori aleatorii utilizate pentru această funcție sunt următoarele:

  • Pe Windows se va utiliza întotdeauna » CryptGenRandom(). Începând cu PHP 7.2.0 se va utiliza întotdeauna » CNG-API.
  • Pe Linux se va utiliza apelul de sistem (syscall) » getrandom(2) dacă este disponibil.
  • Pe alte platforme se va utiliza /dev/urandom.
  • Dacă nici una din sursele menționate nu sunt disponibile, va fi emisă o excepție Exception.

Notă: Cu toate că această funcție a fost adăugată în PHP 7.0, o » implementare în spațiul utilizatorului este disponibilă pentru PHP de la versiunea 5.2 până la 5.6 inclusiv.

Parametri

length

The length of the random string that should be returned in bytes.

Valorile întoarse

Returns a string containing the requested number of cryptographically secure random bytes.

Erori/Excepții

  • Dacă nu poate fi găsită o sursă potrivită de valori aleatorii, va fi emisă o excepție Exception.
  • Dacă sunt furnizați parametri incorecți, va fi emisă o excepție TypeError.
  • If an invalid length of bytes is given, an Error will be thrown.

Exemple

Example #1 random_bytes() example

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

Exemplul de mai sus va afișa ceva similar cu:

string(10) "385e33f741"

A se vedea și

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