39

Or is there a software to auto generate random passwords?

Pool
  • 11,999
  • 14
  • 68
  • 78
user198729
  • 61,774
  • 108
  • 250
  • 348

19 Answers19

97

Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length. Here's an example in PHP:

function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.

Matheus Gontijo
  • 1,178
  • 1
  • 12
  • 29
Matt Huggins
  • 81,398
  • 36
  • 149
  • 218
  • An alternative could always be to str_shuffle() the string and select random characters if you want more randomization. – David Dec 03 '09 at 03:35
  • Adding on to David's comment, you could easily just do something like... $chars = 'blah'; return substr( str_shuffle( $chars ), 0, $length ); and make your function two lines. – William Dec 03 '09 at 03:46
  • 9
    I would remove the vowels because the wrong people will always get the bad results (it has happened twice to me). – MathGladiator Dec 03 '09 at 04:10
  • 4
    It's more academic to bring this up, but in any solution that uses a (deterministic) php-based function (rand() or a hash function), it's a pseudo-random, not true random-seeded algorithm. You could replace that portion with an API call to an atmospheric noise-based web service (e.g. http://www.random.org/clients/http/ ) Granted, probably not worth the added dependency for the difference in randomness in most cases. – micahwittman Dec 03 '09 at 04:31
  • 6
    @William - simply using str_shuffle won't be as random, as you'll end up with zero or one "a", zero or one "b", zero or one "c", etc. You will never have repeat characters, which decreases the value significantly in my opinion. – Matt Huggins Dec 03 '09 at 05:11
  • 14
    if you do go with a method like this, i'd recommend removing all vowels, as well as `l`, `1`, `0` and `o`, since they can be confusing for users, depending on your font. – nickf Dec 03 '09 at 08:45
  • 2
    @nickf's tip is great for another reason as well. I like to avoid generating swear words for the PC minded folks. You'd be surprised how often you can generate naughty words with vowels included. – Joel Mellon Nov 13 '12 at 17:24
  • @micahwittman better than rand is probably openssl_random_pseudo_bytes() – willbradley Nov 20 '15 at 19:41
  • @nickf also capital i "I" – Islam Abdalla Feb 22 '17 at 10:37
12

Here's a simple solution. It will contain lowercase letters and numbers.

substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);

Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.

function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}
Dolph
  • 49,714
  • 13
  • 63
  • 88
6

I want to play the game. The simplest way would be to do:

function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
    return substr( str_shuffle( $chars ), 0, $length );
}

This is pretty much just a modification of the first answer. Specify the characters you want in the second parameters and the length of the password in the first.

William
  • 15,465
  • 8
  • 36
  • 32
  • 6
    This is just a repeat comment that I posted in response to your comment on my answer: Simply using str_shuffle won't be as random, as you'll end up with zero or one "a", zero or one "b", zero or one "c", etc. You will never have repeat characters, which decreases the value significantly in my opinion. – Matt Huggins Dec 03 '09 at 05:12
  • 1
    http://php.net/manual/en/function.str-shuffle.php - Says that `str_shuffle` does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead. – Eugene Mala Oct 02 '16 at 15:27
5

This is how I do it.

$pw = ""; 
for ($i = 0; $i < 13; $i++)
{
    $pw .= chr(rand(33, 126));
}
fooSolver
  • 61
  • 1
  • 4
3

here is a function that generates a password with a minimum length, a minimum number of digits and a minimal number of letters.

function generatePassword() {
$min_length=8;  //Minimum length of the password
$min_numbers=2; //Minimum of numbers AND special characters
$min_letters=2; //Minimum of letters

$password = '';
$numbers=0;
$letters=0;
$length=0;

while ( $length <= $min_length OR $numbers <= $min_numbers OR $letters <= $min_letters) {
    $length+=1;
    $type=rand(1, 3);
    if ($type==1) {
        $password .= chr(rand(33, 64)); //Numbers and special characters
        $numbers+=1;
    }elseif ($type==2) {
        $password .= chr(rand(65, 90)); //A->Z
        $letters+=1;
    }else {
        $password .= chr(rand(97, 122)); //a->z
        $letters+=1;
    }

}
return $password;   
}
Ronan Corre
  • 121
  • 1
  • 4
3

Another, very simple (and secure!) way to do this is the following (I generate all my own passwords that way):

base64_encode(random_bytes(12));

This generates a 16 character password that uses quite a sane range of characters.

However, depending on your requirements (for example if a user needs to type in their password), it may be desirable to remove characters that migth be confused (such as l, I, 1, 0, O, 5, S, and so on). In that case, the above solution is probably a bit too simple.

Dave Vogt
  • 18,600
  • 7
  • 42
  • 54
2

A good password should be a mixture of both uppercase, lowercase, has number, letters, has special characters and its more than 6 characters long. Here is function I use on my apps.

function randomPassword( $length = 8 ) 
{ 
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?"; 
$length = rand(10, 16); 
$password = substr( str_shuffle(sha1(rand() . time()) . $chars ), 0, $length );
 return $password;
}
1

Also you can try a function that I wrote and is available form my blog. Advantage of this function is that it gives equal importance to lowercase, uppercase, numbers and special characters. It can be found here PHP random password generator function

Jaspreet Chahal
  • 2,759
  • 1
  • 15
  • 17
1

I like to shuffle array of random chars

$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
echo implode($a); //maxlength
echo "\n".substr( implode($a), 0, 10 ); //instead of 10 => any length

//As function:
function getMeRandomPwd($length){
    $a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789"); 
    shuffle($a);
    return substr( implode($a), 0, $length );
}
echo "\n".getMeRandomPwd(8)."\n".getMeRandomPwd(11);
// Outpus something like:
// 3Ai4Xf6R2I8bYGUmKgB9jpqo7ncV5teuQhkOHJCNrTP0sLFd1wxSMlEWvyaD
// 3Ai4Xf6R2I
// JsBKWFDa
// gfxsjr3dX70

If you need the password to be longer, just concatenate charlist a few times :)

jave.web
  • 13,880
  • 12
  • 91
  • 125
1
function generate_password($length = 6) {
    $password = '';
    $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
    for ($i = 0; $i < $length; $i ++) {
        $password .= $chars[array_rand($chars)];
    }
    return $password;
}
Alex S
  • 719
  • 6
  • 8
1

This function will include half digits and half numbers:

     function generateMixedPassword($length = 8) {
        $base = 'abcdefghijklmnopqrstuvwxyz';
        $baseD = '0123456789';

        $r = array();

        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($base, rand(0, strlen($base) - 1), 1);
        }
        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($baseD, rand(0, strlen($baseD) - 1), 1);
        }
        shuffle($r);

        return implode('', $r);
    }

Using the same login, it can be extended to also include special characters

Aris
  • 4,643
  • 1
  • 41
  • 38
0

Pwgen-php produces save, pronounceable (easier to remember) passwords: http://code.google.com/p/pwgen-php/

Might that be acceptable?

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101
0

You could just use PEAR's Text_Password package - it supports quite a few algorithms for generating them; and frees up your time to go onto something else.

kguest
  • 3,804
  • 3
  • 29
  • 31
0

This function will generate more stronger password than most woted solution:

function generatePassword($size=8){
    $p = openssl_random_pseudo_bytes(ceil($size*0.67), $crypto_strong);
    $p = str_replace('=', '', base64_encode($p));
    $p = strtr($p, '+/', '^*');
    return substr($p, 0, $size);      
}

Each character of password will be [A-Z] or [a-z] or ^ or *

Eugene Mala
  • 1,081
  • 12
  • 25
0

This will help to create random password:

<?php
function generatePassword ($length = 8)
{
  $genpassword = "";
  $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
  $i = 0; 
  while ($i < $length) { 
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    if (!strstr($genpassword, $char)) { 
      $genpassword .= $char;
      $i++;
    }
  }
  return $genpassword;
} 
?>
<input type="text" value="<?php echo generatePassword(); ?>">
Zoe
  • 27,060
  • 21
  • 118
  • 148
M. Lak
  • 903
  • 9
  • 18
0

use hackzilla/password-generator

it has many options to create different kind of passwords:

  • ComputerPasswordGenerator()
  • HybridPasswordGenerator() -> sjgX-PFjH-zxMz-PRDz-G6mx-wMJ4-ST24
  • HumanPasswordGenerator() -> Verkuemmerungen-verlottertet-dreinzuschauen (word list based. in this case a german word list)
  • RequirementPasswordGenerator()

ComputerPasswordGenerator

$generator
  ->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
;

$password = $generator->generatePassword();

RequirementPasswordGenerator

$generator
  ->setLength(16)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_SYMBOLS, true)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 2)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 8)
;

$password = $generator->generatePassword();
c33s
  • 2,612
  • 1
  • 30
  • 43
0

I use st_split and implode function:

function genarateKey(){
    $limit= 8;
    $chars= 'abcdefghijklmnopqrstuvxwyz1234567890!@#$%^&*()_+=-[]{}\|ABCDEFGHIJKLMNOPQRSTUVXWYZ';
    $chararray= str_split($chars);
    $gen=array();
    for($i=0;$i<$limit;$i++){
        $index=rand(0,strlen($chars)-1);
        $gen[$i]= $chararray[$index];
    }
    return implode($gen); //converts array to string
}
princebillyGK
  • 2,917
  • 1
  • 26
  • 20
0

Memorable password generator

function password($length)
  {
    $vowel = array(
        'a',
        'e',
        'i',
        'o',
        'u',
    );

    $consonant = array(
        'b',
        'c',
        'd',
        'f',
        'g',
        'h',
        'j',
        'k',
        'l',
        'm',
        'n',
        'p',
        'q',
        'r',
        's',
        't',
        'v',
        'w',
        'x',
        'y',
        'z',
    );

    $result = '';
    for ($i = 0; $i < $length; $i++) {
        if ($i % 2 == 0) {
            $result .= $consonant[rand(0, 15)];
        } else {
            $result .= $vowel[rand(0, 4)];
        }
    }

    return $result;
}

The result:

password(8);//kutekaku
password(11);//rahubabatul
0

I think better way to generate random password is below function, if someone want then you can use these for strong password

public function randPassword($upper = 2, $lower = 3, $numeric = 2, $other = 1) { 

        $pass_order = Array(); 
        $passWord = ''; 

        //Create contents of the password 
        for ($i = 0; $i < $upper; $i++) { 
            $pass_order[] = chr(rand(65, 90)); 
        } 
        for ($i = 0; $i < $lower; $i++) { 
            $pass_order[] = chr(rand(97, 122)); 
        } 
        for ($i = 0; $i < $numeric; $i++) { 
            $pass_order[] = chr(rand(48, 57)); 
        } 
        for ($i = 0; $i < $other; $i++) { 
            $pass_order[] = chr(rand(33, 47)); 
        } 

        //using shuffle() to shuffle the order
        shuffle($pass_order); 

        //Final password string 
        foreach ($pass_order as $char) { 
            $passWord .= $char; 
        } 
        return $passWord; 
    } 
nageen nayak
  • 1,262
  • 2
  • 18
  • 28