random_bytes

(PHP 7, PHP 8)

random_bytesGet cryptographically secure random bytes

Beschreibung

random_bytes(int $length): string

Generates a string containing uniformly selected random bytes with the requested length.

As the returned bytes are selected completely randomly, the resulting string is likely to contain unprintable characters or invalid UTF-8 sequences. It may be necessary to encode it before transmission or display.

The randomness generated by this function is suitable for all applications, including the generation of long-term secrets, such as encryption keys.

Die Zufallsquellen in der Reihenfolge ihrer Priorität sind folgende:

  • Linux: » getrandom(), /dev/urandom

  • FreeBSD >= 12 (PHP >= 7.3): » getrandom(), /dev/urandom

  • Windows (PHP >= 7.2): » CNG-API

    Windows: » CryptGenRandom

  • macOS (PHP >= 8.2; >= 8.1.9; >= 8.0.22 wenn CCRandomGenerateBytes bei der Kompilierung verfügbar ist): CCRandomGenerateBytes()

    macOS (PHP >= 8.1; >= 8.0.2): arc4random_buf(), /dev/urandom

  • NetBSD >= 7 (PHP >= 7.1; >= 7.0.1): arc4random_buf(), /dev/urandom

  • OpenBSD >= 5.5 (PHP >= 7.1; >= 7.0.1): arc4random_buf(), /dev/urandom

  • DragonflyBSD (PHP >= 8.1): » getrandom(), /dev/urandom

  • Solaris (PHP >= 8.1): » getrandom(), /dev/urandom

  • Jede beliebige Kombination von Betriebssystem und PHP-Version, die oben nicht erwähnt wurde: /dev/urandom
  • Wenn keine der Quellen verfügbar ist oder keine davon Zufälligkeit erzeugen kann, wird eine Random\RandomException ausgelöst.

Hinweis: Obwohl diese Funktion erst mit PHP 7.0.0 in PHP hinzugefügt wurde, gibt es » Userland-Implementierungen für PHP 5.2 bis einschließlich 5.6.

Parameter-Liste

length

The length of the random string that should be returned in bytes; must be 1 or greater.

Rückgabewerte

A string containing the requested number of cryptographically secure random bytes.

Fehler/Exceptions

  • Wenn keine angemessene Quelle für Zufallszahlen verfügbar ist, wird eine Random\RandomException geworfen.
  • If the value of length is less than 1, a ValueError will be thrown.

Changelog

Version Beschreibung
8.2.0 In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

Beispiele

Beispiel #1 random_bytes() example

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

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

string(10) "385e33f741"

Siehe auch

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