如何用PHP生成随机密码?

时间:2009-12-03 03:24:23

标签: php random passwords

或者是否有自动生成随机密码的软件?

20 个答案:

答案 0 :(得分:96)

只需构建一个随机a-zA-Z0-9或任何您想要的)的字符串,直到达到所需的长度。这是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;
}

要进行优化,如果您在单次执行期间多次调用此函数,则可以在方法(或父类)中将$chars定义为静态变量或常量。

答案 1 :(得分:12)

这是一个简单的解决方案。它将包含小写字母和数字。

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

这是一个更强大的解决方案,可以在所需范围内随机生成所需字符范围内的字符代码。

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;
}

答案 2 :(得分:6)

我想玩这个游戏。最简单的方法是:

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

这几乎只是对第一个答案的修改。在第二个参数中指定所需的字符,在第一个参数中指定密码的长度。

答案 3 :(得分:4)

我就是这样做的。

$pw = ""; 
for ($i = 0; $i < 13; $i++)
{
    $pw .= chr(rand(33, 126));
}

答案 4 :(得分:3)

$password = hash('sha512', rand());

不应该太难记住。这可能更容易记住:

$password = substr(hash('sha512',rand()),0,12); // Reduces the size to 12 chars

只使用了16个可能的字符,但这仍然是16 ^ 12个可能的密码(每秒300,000个密码,需要29 years才能破解。)

答案 5 :(得分:2)

一个好的密码应该是大写,小写,有数字,字母,有特殊字符和长度超过6个字符的混合。这是我在我的应用程序中使用的功能。

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

答案 6 :(得分:2)

这是一个生成密码的函数,该密码的长度最小,位数最少,字母最少。

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;   
}

答案 7 :(得分:1)

此外,您可以尝试我编写的功能,并可从我的博客中获取。此功能的优点在于它同样重视小写,大写,数字和特殊字符。在这里能找到它 PHP random password generator function

答案 8 :(得分:1)

我喜欢随机播放数组

$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

如果您需要更长的密码,只需连接几次charlist:)

答案 9 :(得分:0)

Pwgen-php产生保存,可发音(易记)的密码: http://code.google.com/p/pwgen-php/

可以接受吗?

答案 10 :(得分:0)

此功能将生成比大多数解决方案更强大的密码:

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);      
}

密码的每个字符都是[A-Z]或[a-z]或^或*

答案 11 :(得分:0)

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;
}

答案 12 :(得分:0)

你可以使用PEAR's Text_Password package - 它支持很多算法来生成它们;并腾出时间去做别的事。

答案 13 :(得分:0)

这将有助于创建随机密码:

<?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(); ?>">

以下是working example (Demo)

答案 14 :(得分:0)

使用hackzilla/password-generator

它有很多选项来创建不同类型的密码:

  • ComputerPasswordGenerator()
  • HybridPasswordGenerator() - &gt; sjgX-PFjH-zxMz-PRDz-G6mx-wMJ4-ST24
  • HumanPasswordGenerator() - &gt; Verkuemmerungen-verlottertet-dreinzuschauen(基于单词列表。在这种情况下是德语单词列表)
  • 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();

答案 15 :(得分:0)

另一种非常简单(且安全!)的方法(我以这种方式生成自己的所有密码)如下:

base64_encode(random_bytes(12));

这将生成一个16个字符的密码,该密码使用相当合理的字符范围。

但是,根据您的要求(例如,如果用户需要输入密码),可能希望删除使米格斯混淆的字符(例如l,I,1、0,O,5,S , 等等)。在这种情况下,上述解决方案可能太简单了。

答案 16 :(得分: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
}

答案 17 :(得分:0)

难忘的密码生成器

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;
}

结果:

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

答案 18 :(得分:0)

此功能将包括半位数和半位数:

     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);
    }

使用相同的登录名,它可以扩展为还包含特殊字符

答案 19 :(得分:0)

我认为生成随机密码的更好方法是在功能下方,如果有人愿意,则可以使用这些密码来获得强密码

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; 
    }