php[tek] 2018 : Call for Speakers

random_bytes

(PHP 7)

random_bytesGenerates cryptographically secure pseudo-random bytes

Beschreibung

string random_bytes ( int $length )

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

Die Zufallsquellen, die für diese Funktion verwendet werden, sind folgende:

  • Unter Windows wird immer CryptGenRandom() verwendet.
  • Auf anderen Plattformen, wird arc4random_buf() verwendet, wenn es verfügbar ist. Dies ist im Allgemeinen nur unter BSD-Derivation oder Systemen mit libbsd der Fall.
  • Schlägt obiges fehl, wird /dev/arandom verwendet, falls verfügbar.
  • Ist /dev/arandom nicht verfügbar, dann wird /dev/urandom als Fallback verwendet.
  • Ist keine der zuvor aufgezählten Quellen verfübar, wird ein Error geworfen.

Hinweis: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive.

Parameter-Liste

length

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

Rückgabewerte

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

Fehler/Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If an invalid length of bytes is given, an Error will be 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 2 notes

up
25
akam at akameng dot com
1 year 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
-1
ccb_bc at hotmail dot com
18 days 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);
        }
    }
To Top