PHP Doku:: Generate a pseudo-random string of bytes - function.openssl-random-pseudo-bytes.html

Verlauf / Chronik / History: (2) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzKryptografische ErweiterungenOpenSSLOpenSSL Funktionenopenssl_random_pseudo_bytes

Ein Service von Reinhard Neidl - Webprogrammierung.

OpenSSL Funktionen

<<openssl_public_encrypt

openssl_seal>>

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytesGenerate a pseudo-random string of bytes

Beschreibung

string openssl_random_pseudo_bytes ( string $length [, bool &$crypto_strong ] )

Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter.

It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old.

Parameter-Liste

length

The length of the desired string of bytes. Must be a positive integer. PHP will try to cast this parameter to a non-null integer to use it.

crypto_strong

If passed into the function, this will hold a boolean value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. TRUE if it did, otherwise FALSE

Rückgabewerte

Returns the generated string of bytes on success, Im Fehlerfall wird FALSE zurückgegeben..

Beispiele

Beispiel #1 openssl_random_pseudo_bytes() example

<?php
for ($i = -1$i <= 4$i++) {
    
$bytes openssl_random_pseudo_bytes($i$cstrong);
    
$hex   bin2hex($bytes);

    echo 
"Lengths: Bytes: $i and Hex: " strlen($hex) . PHP_EOL;
    
var_dump($hex);
    
var_dump($cstrong);
    echo 
PHP_EOL;
}
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Lengths: Bytes: -1 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)

Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)

Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)

Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)

Siehe auch

  • bin2hex() - Wandelt Binär-Daten in ihre hexadezimale Entsprechung um
  • crypt() - Einweg-String-Verschlüsselung (Hashbildung)
  • mt_rand() - Erzeugt "bessere" Zufallszahlen
  • uniqid() - Erzeugt eine eindeutige ID

4 BenutzerBeiträge:
- Beiträge aktualisieren...
acatalept at gmail
11.01.2011 20:24
FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable.  It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it's a known problem with OpenSSL (not PHP specifically).

See: http://www.google.com/search?q=openssl_random_pseudo_bytes+slow
gorgo
17.03.2010 11:47
a simple way to generate a random password is:
<?php
$password
= base64_encode(openssl_random_pseudo_bytes($length, $strong));
?>

this function generates a password with a fallback to mt_rand() if no openssl is available:
<?php
/**
 * generates a random password, uses base64: 0-9a-zA-Z/+
 * @param int [optional] $length length of password, default 24 (144 Bit)
 * @return string password
 */
function generatePassword($length = 24) {
        if(
function_exists('openssl_random_pseudo_bytes')) {
           
$password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
            if(
$strong == TRUE)
                return
substr($password, 0, $length); //base64 is about 33% longer, so we need to truncate the result
       
}
       
       
//fallback to mt_rand if php < 5.3 or no openssl available
       
$characters = '0123456789';
       
$characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
       
$charactersLength = strlen($characters)-1;
       
$password = '';

       
//select some random characters
       
for ($i = 0; $i < $length; $i++) {
           
$password .= $characters[mt_rand(0, $charactersLength)];
        }       
       
        return
$password;
}
?>

note: openssl_random_pseudo_bytes() is considerably slower than mt_rand.
Tyler Larson
22.08.2009 0:18
Here's a drop-in replacement for rand() using OpenSSL as your PRNG:

<?php
   
function crypto_rand($min,$max) {
       
$range = $max - $min;
        if (
$range == 0) return $min; // not so random...
       
$length = (int) (log($range,2) / 8) + 1;
        return
$min + (hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s))) % $range);
    }
?>
Tyler Larson
21.08.2009 23:29
If you don't have this function but you do have OpenSSL installed, you can always fake it:

<?php
   
function openssl_random_pseudo_bytes($length) {
       
$length_n = (int) $length; // shell injection is no fun
       
$handle = popen("/usr/bin/openssl rand $length_n", "r");
       
$data = stream_get_contents($handle);
       
pclose($handle);
        return
$data;
    }
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)