Advertisement
Guest User

Secure random password generator

a guest
Feb 20th, 2013
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. /**
  2.  * Generates and returns a random password, of a random length between min and max.
  3.  *
  4.  * Hard limits are minimum 10 chars and maximum 72.
  5.  *
  6.  * @author Christian Fagerheim (Fagerheim Software)
  7.  * @link www.fagsoft.no
  8.  * @license Creative Commons Attribution-ShareAlike 3.0. http://creativecommons.org/licenses/by-sa/3.0/.
  9.  *
  10.  * @param int[optional] $minLen = 10
  11.  * @param int[optional] $maxLen = 14
  12.  * @return string
  13.  */
  14. function generatePassword ($minLen = 10, $maxLen = 14) {
  15.     if ($minLen < 10) {
  16.         $minLen = 10;
  17.     }
  18.  
  19.     // Discard everything above 72 characters for the password (bcrypt limitation).
  20.     if ($maxLen > 72) {
  21.         $maxLen = 72;
  22.     }
  23.  
  24.     $numChars = mt_rand ($minLen, $maxLen);
  25.  
  26.     // Create an secure random password, and cut it down to length.
  27.     $password = base64_encode (mcrypt_create_iv (256, MCRYPT_DEV_URANDOM));
  28.     $password = substr ($password, 0, $numChars);
  29.  
  30.     // Define the replacements sets and values for strtr ().
  31.     $find = "10lIO";
  32.     $replace = "_-*!?";
  33.  
  34.     // Replace the similar-looking characters with special characters.
  35.     $password = strtr ($find, $replace, $password);
  36.  
  37.     // Save the hashed password in the object, and return it to calling method.
  38.     return $password;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement