random_bytes

(PHP 7, PHP 8)

random_bytesПолучает криптографически безопасные случайные байты

Описание

random_bytes(int $length): string

Создаёт строку, содержащую равномерно выбранные случайные байты с запрошенной длиной length.

Поскольку возвращаемые байты выбираются совершенно случайно, полученная строка может содержать непечатаемые символы или недопустимые последовательности UTF-8. Может потребоваться её кодирование перед передачей или отображением.

Случайная последовательность, создаваемая функцией, подходит для всех приложений, включая генерацию долгосрочных секретов, таких как ключи шифрования.

Источники случайных величин в порядке приоритета:

  • 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, если CCRandomGenerateBytes доступен во время компиляции): 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

  • Любая комбинация операционной системы и версии PHP, не указанная ранее: /dev/urandom
  • Если ни один из источников не доступен или все они не генерируют случайную величину, то будет выброшено исключение Random\RandomException.

Замечание: Эта функция была добавлена в PHP 7.0, а для версий с 5.2 по 5.6 включительно доступна » пользовательская реализация.

Список параметров

length

Длина генерируемой строки в байтах; должно быть 1 или больше.

Возвращаемые значения

Возвращает строку, состоящую из заданного количества криптографически безопасных байт.

Ошибки

  • Если подходящие источники случайных величин отсутствуют, то выбрасывается исключение Random\RandomException.
  • Если значение параметра length меньше 1, будет выброшена ошибка ValueError.

Список изменений

Версия Описание
8.2.0 В случае возникновения ошибки CSPRNG, функция теперь будет выбрасывать исключение Random\RandomException. Ранее выбрасывалось исключение Exception.

Примеры

Пример #1 Пример использования random_bytes()

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

Вывод приведённого примера будет похож на:

string(10) "385e33f741"

Смотрите также

  • Random\Randomizer::getBytes() - Получает случайные байты
  • random_int() - Получает криптографически безопасное равномерно выбранное целое число
  • bin2hex() - Преобразовывает бинарные данные в шестнадцатеричное представление
  • base64_encode() - Кодирует данные в формат MIME base64
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