note 96812 added to function.openssl-random-pseudo-bytes
| From: | gorgo at osu1 dot php dot net | Date: | Wed, 17 Mar 2010 10:47:23 +0000 |
| Subject: | note 96812 added to function.openssl-random-pseudo-bytes | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-167127@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 85.214.154.209
Probable Submitter: 217.243.204.99
----
Manual Page -- http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php
Edit -- https://master.php.net/note/edit/96812
Del: integrated -- https://master.php.net/note/delete/96812/integrated
Del: useless -- https://master.php.net/note/delete/96812/useless
Del: bad code -- https://master.php.net/note/delete/96812/bad+code
Del: spam -- https://master.php.net/note/delete/96812/spam
Del: non-english -- https://master.php.net/note/delete/96812/non-english
Del: in docs -- https://master.php.net/note/delete/96812/in+docs
Del: other reasons-- https://master.php.net/note/delete/96812
Reject -- https://master.php.net/note/reject/96812
Search -- https://master.php.net/manage/user-notes.php