在php中生成随机密码

发布于 2024-11-09 02:20:26 字数 376 浏览 0 评论 0原文

我正在尝试在 php.ini 中生成随机密码。

然而,我得到了所有的“a”,并且返回类型是数组类型,我希望它是一个字符串。关于如何纠正代码有什么想法吗?

谢谢。

function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, count($alphabet)-1);
        $pass[$i] = $alphabet[$n];
    }
    return $pass;
}

I am trying to generate a random password in php.

However I am getting all 'a's and the return type is of type array and I would like it to be a string. Any ideas on how to correct the code?

Thanks.

function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, count($alphabet)-1);
        $pass[$i] = $alphabet[$n];
    }
    return $pass;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

开始看清了 2024-11-16 02:20:26

安全警告rand() 不是加密安全的伪随机数生成器。在其他地方寻找在 PHP 中生成加密安全的伪随机字符串

试试这个(使用 strlen 而不是 count,因为字符串上的 count 始终为 1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

演示

Security warning: rand() is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.

Try this (use strlen instead of count, because count on a string is always 1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

Demo

忘东忘西忘不掉你 2024-11-16 02:20:26

TL;DR:

  • 使用 random_int() 和下面给定的 random_str()
  • 如果您没有 random_int(),请使用 random_compat

说明:

由于您要生成密码,因此需要确保生成的密码是不可预测的,并且确保此属性出现在您的实现中的唯一方法是使用 加密安全伪随机数生成器(CSPRNG)。

对于随机字符串的一般情况,可以放宽对 CSPRNG 的要求,但在涉及安全性时则不然。

在 PHP 中生成密码的简单、安全且正确的答案是使用 RandomLib 并且不要重新发明车轮。该库已经过行业安全专家以及我自己的审核。

对于喜欢发明自己的解决方案的开发人员,PHP 7.0.0 将提供 random_int() 为此目的。如果您仍在使用 PHP 5.x,我们为 random_int() 编写了PHP 5 polyfill 这样您就可以在 PHP 7 发布之前使用新的 API。使用我们的 random_int() polyfill可能比编写自己的实现更安全。

有了安全随机整数生成器,生成安全随机字符串比馅饼更容易:

<?php
/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

TL;DR:

  • Use random_int() and the given random_str() below.
  • If you don't have random_int(), use random_compat.

Explanation:

Since you are generating a password, you need to ensure that the password you generate is unpredictable, and the only way to ensure this property is present in your implementation is to use a cryptographically secure pseudorandom number generator (CSPRNG).

The requirement for a CSPRNG can be relaxed for the general case of random strings, but not when security is involved.

The simple, secure, and correct answer to password generation in PHP is to use RandomLib and don't reinvent the wheel. This library has been audited by industry security experts, as well as myself.

For developers who prefer inventing your own solution, PHP 7.0.0 will provide random_int() for this purpose. If you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API before PHP 7 is released. Using our random_int() polyfill is probably safer than writing your own implementation.

With a secure random integer generator on hand, generating a secure random string is easier than pie:

<?php
/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}
寒江雪… 2024-11-16 02:20:26

我知道您正在尝试以特定方式生成密码,但您可能也想看看这个方法...

$bytes = openssl_random_pseudo_bytes(2);

$pwd = bin2hex($bytes);

它取自 php.net 站点,它创建一个字符串,其长度是您输入的数字的两倍放入 openssl_random_pseudo_bytes 函数。因此上面将创建一个 4 个字符长的密码。

简而言之...

$pwd = bin2hex(openssl_random_pseudo_bytes(4));

将创建一个 8 个字符长的密码。

但请注意,密码仅包含数字 0-9 和小写字母 af!

I know you are trying to generate your password in a specific way, but you might want to look at this method as well...

$bytes = openssl_random_pseudo_bytes(2);

$pwd = bin2hex($bytes);

It's taken from the php.net site and it creates a string which is twice the length of the number you put in the openssl_random_pseudo_bytes function. So the above would create a password 4 characters long.

In short...

$pwd = bin2hex(openssl_random_pseudo_bytes(4));

Would create a password 8 characters long.

Note however that the password only contains numbers 0-9 and small cap letters a-f!

疧_╮線 2024-11-16 02:20:26

2 行的小代码。

演示:http://codepad.org/5rHMHwnH

function rand_string( $length ) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return substr(str_shuffle($chars),0,$length);

}

echo rand_string(8);

使用 rand_string 您可以定义将创建多少字符。

Tiny code with 2 line.

demo: http://codepad.org/5rHMHwnH

function rand_string( $length ) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return substr(str_shuffle($chars),0,$length);

}

echo rand_string(8);

with rand_string you can define how much character will be create.

久光 2024-11-16 02:20:26

如果您使用的是 PHP7,则可以使用 random_int() 函数:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[random_int(0, $max)];

  return $str;
}

下面是旧答案:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[mt_rand(0, $max)];

  return $str;
}

If you are on PHP7 you could use the random_int() function:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[random_int(0, $max)];

  return $str;
}

Old answer below:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[mt_rand(0, $max)];

  return $str;
}
半夏半凉 2024-11-16 02:20:26

一行:

substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') , 0 , 10 )

In one line:

substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') , 0 , 10 )
若沐 2024-11-16 02:20:26

您最好的选择是ircmaxell 的RandomLib 库

用法示例:

$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));

$passwordLength = 8; // Or more
$randomPassword = $generator->generateString($passwordLength);

它生成的字符串比普通随机函数(如 shuffle()rand())具有更强的随机性(这正是您通常需要的密码等敏感信息) 、盐和键)。

Your best bet is the RandomLib library by ircmaxell.

Usage example:

$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));

$passwordLength = 8; // Or more
$randomPassword = $generator->generateString($passwordLength);

It produces strings which are more strongly random than the normal randomness functions like shuffle() and rand() (which is what you generally want for sensitive information like passwords, salts and keys).

初雪 2024-11-16 02:20:26

我将发布一个答案,因为现有的一些答案很接近,但具有以下之一:

  • 字符空间比您想要的更小,以便暴力破解更容易,或者对于相同的熵,密码必须更长
  • RNG 不被认为是
  • 某些第三方库的加密安全要求,我认为展示它可能很有趣自己做可能需要什么

这个答案将规避 count/strlen 问题,因为生成的密码的安全性(至少恕我直言)超越了您的实现方式。我还将假设 PHP > 5.3.0。

让我们将问题分解为以下几个组成部分:

  1. 使用一些安全的随机源来获取随机数据
  2. 使用该数据并将其表示为一些可打印的字符串

对于第一部分,PHP > 5.3.0 提供函数 openssl_random_pseudo_bytes 。请注意,虽然大多数系统使用加密强度较高的算法,但您必须进行检查,以便我们使用包装器:

/**
 * @param int $length
 */
function strong_random_bytes($length)
{
    $strong = false; // Flag for whether a strong algorithm was used
    $bytes = openssl_random_pseudo_bytes($length, $strong);

    if ( ! $strong)
    {
        // System did not use a cryptographically strong algorithm 
        throw new Exception('Strong algorithm not available for PRNG.');
    }        

    return $bytes;
}

对于第二部分,我们将使用 base64_encode 因为它需要一个字节字符串,并且会生成一系列字符,这些字符的字母表非常接近于原来的问题。如果我们不介意最终字符串中出现 +/= 字符,并且我们希望结果至少为 $ n 个字符长,我们可以简单地使用:

base64_encode(strong_random_bytes(intval(ceil($n * 3 / 4))));

3/4 因子是由于 Base64 编码导致的字符串长度至少比字节字符串大三分之一。如果 $n 是 4 的倍数且最多长 3 个字符,则结果将是准确的。由于额外的字符主要是填充字符 =,如果我们出于某种原因限制密码的长度是精确的,那么我们可以将其截断为我们想要的长度。这尤其是因为对于给定的 $n,所有密码都将以相同的数字结尾,因此有权访问结果密码的攻击者最多可以少 2 个字符进行猜测。


为了额外的好处,如果我们想满足OP问题中的确切规格,那么我们将不得不做更多的工作。我将放弃这里的基本转换方法,并采用一种快速而肮脏的方法。由于字母表有 62 个条目,两者都需要生成比结果中使用的随机性更多的随机性。

对于结果中的额外字符,我们可以简单地将它们从结果字符串中丢弃。如果我们从字节串中的 8 个字节开始,那么最多大约 25% 的 Base64 字符将是这些“不需要的”字符,因此简单地丢弃这些字符会得到一个不短于 OP 所需的字符串。然后我们可以简单地截断它以达到精确的长度:

$dirty_pass = base64_encode(strong_random_bytes(8)));
$pass = substr(str_replace(['/', '+', '='], ['', '', ''], $dirty_pass, 0, 8);

如果您生成更长的密码,填充字符 = 在中间结果中所占的比例越来越小,以便您可以实现更精简的方法,如果需要考虑耗尽用于 PRNG 的熵池。

I'm going to post an answer because some of the existing answers are close but have one of:

  • a smaller character space than you wanted so that either brute-forcing is easier or the password must be longer for the same entropy
  • a RNG that isn't considered cryptographically secure
  • a requirement for some 3rd party library and I thought it might be interesting to show what it might take to do it yourself

This answer will circumvent the count/strlen issue as the security of the generated password, at least IMHO, transcends how you're getting there. I'm also going to assume PHP > 5.3.0.

Let's break the problem down into the constituent parts which are:

  1. use some secure source of randomness to get random data
  2. use that data and represent it as some printable string

For the first part, PHP > 5.3.0 provides the function openssl_random_pseudo_bytes. Note that whilst most systems use a cryptographically strong algorithm, you have to check so we'll use a wrapper:

/**
 * @param int $length
 */
function strong_random_bytes($length)
{
    $strong = false; // Flag for whether a strong algorithm was used
    $bytes = openssl_random_pseudo_bytes($length, $strong);

    if ( ! $strong)
    {
        // System did not use a cryptographically strong algorithm 
        throw new Exception('Strong algorithm not available for PRNG.');
    }        

    return $bytes;
}

For the second part, we'll use base64_encode since it takes a byte string and will produce a series of characters that have an alphabet very close to the one specified in the original question. If we didn't mind having +, / and = characters appear in the final string and we want a result at least $n characters long, we could simply use:

base64_encode(strong_random_bytes(intval(ceil($n * 3 / 4))));

The 3/4 factor is due to the fact that base64 encoding results in a string that has a length at least a third bigger than the byte string. The result will be exact for $n being a multiple of 4 and up to 3 characters longer otherwise. Since the extra characters are predominantly the padding character =, if we for some reason had a constraint that the password be an exact length, then we can truncate it to the length we want. This is especially because for a given $n, all passwords would end with the same number of these, so that an attacker who had access to a result password, would have up to 2 less characters to guess.


For extra credit, if we wanted to meet the exact spec as in the OP's question then we would have to do a little bit more work. I'm going to forgo the base conversion approach here and go with a quick and dirty one. Both need to generate more randomness than will be used in the result anyway because of the 62 entry long alphabet.

For the extra characters in the result, we can simply discard them from the resulting string. If we start off with 8 bytes in our byte-string, then up to about 25% of the base64 characters would be these "undesirable" characters, so that simply discarding these characters results in a string no shorter than the OP wanted. Then we can simply truncate it to get down to the exact length:

$dirty_pass = base64_encode(strong_random_bytes(8)));
$pass = substr(str_replace(['/', '+', '='], ['', '', ''], $dirty_pass, 0, 8);

If you generate longer passwords, the padding character = forms a smaller and smaller proportion of the intermediate result so that you can implement a leaner approach, if draining the entropy pool used for the PRNG is a concern.

故人如初 2024-11-16 02:20:26

您需要 strlen($alphabet),而不是常量 alphabetcount(相当于 'alphabet')。

但是,rand 不是适合此目的的随机函数。它的输出可以很容易地预测,因为它隐式地以当前时间为种子。此外,rand 在加密上并不安全;因此,从输出确定其内部状态相对容易。

相反,从 /dev/urandom 读取以获取加密随机数据。

You want strlen($alphabet), not count of the constant alphabet (equivalent to 'alphabet').

However, rand is not a suitable random function for this purpose. Its output can easily be predicted as it is implicitly seeded with the current time. Additionally, rand is not cryptographically secure; it is therefore relatively easy to determine its internal state from output.

Instead, read from /dev/urandom to get cryptographically random data.

薄凉少年不暖心 2024-11-16 02:20:26

聪明一点:

function strand($length){
  if($length > 0)
    return chr(rand(33, 126)) . strand($length - 1);
}

此处在线查看。

Being a little smarter:

function strand($length){
  if($length > 0)
    return chr(rand(33, 126)) . strand($length - 1);
}

check it here online.

最偏执的依靠 2024-11-16 02:20:26

base_convert(uniqid('pass', true), 10, 36);

例如。 e0m6ngefmj4

编辑

正如我在评论中提到的,长度意味着暴力攻击比定时攻击更有效,因此不必担心“安全性如何”随机生成器是。”专门针对此用例的安全性需要补充可用性,因此上述解决方案实际上足以解决所需的问题。

然而,以防万一您在搜索安全随机字符串生成器时偶然发现了这个答案(我假设有些人基于响应),对于生成令牌之类的东西,以下是此类代码的生成器的样子:

function base64urlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function secureId($length = 32) {

    if (function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes($length);
        return rtrim(strtr(base64_encode($bytes), '+/', '0a'), '=');
    }
    else { // fallback to system bytes

        error_log("Missing support for openssl_random_pseudo_bytes");

        $pr_bits = '';

        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, $length);
            @fclose($fp);
        }

        if (strlen($pr_bits) < $length) {
            error_log('unable to read /dev/urandom');
            throw new \Exception('unable to read /dev/urandom');
        }

        return base64urlEncode($pr_bits);
    }
}

base_convert(uniqid('pass', true), 10, 36);

eg. e0m6ngefmj4

EDIT

As I've mentioned in comments, the length means that brute force attacks would work better against it then timing attacks so it's not really relevant to worry about "how secure the random generator was." Security, specifically for this use case, needs to complement usability so the above solution is actually good enough for the required problem.

However, just in case you stumbled upon this answer while searching for a secure random string generator (as I assume some people have based on the responses), for something such as generating tokens, here is how a generator of such codes would look like:

function base64urlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function secureId($length = 32) {

    if (function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes($length);
        return rtrim(strtr(base64_encode($bytes), '+/', '0a'), '=');
    }
    else { // fallback to system bytes

        error_log("Missing support for openssl_random_pseudo_bytes");

        $pr_bits = '';

        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, $length);
            @fclose($fp);
        }

        if (strlen($pr_bits) < $length) {
            error_log('unable to read /dev/urandom');
            throw new \Exception('unable to read /dev/urandom');
        }

        return base64urlEncode($pr_bits);
    }
}
围归者 2024-11-16 02:20:26

另一种(仅限 Linux)

function randompassword()
{
    $fp = fopen ("/dev/urandom", 'r');
    if (!$fp) { die ("Can't access /dev/urandom to get random data. Aborting."); }
    $random = fread ($fp, 1024); # 1024 bytes should be enough
    fclose ($fp);
    return trim (base64_encode ( md5 ($random, true)), "=");
}

Another one (linux only)

function randompassword()
{
    $fp = fopen ("/dev/urandom", 'r');
    if (!$fp) { die ("Can't access /dev/urandom to get random data. Aborting."); }
    $random = fread ($fp, 1024); # 1024 bytes should be enough
    fclose ($fp);
    return trim (base64_encode ( md5 ($random, true)), "=");
}
好听的两个字的网名 2024-11-16 02:20:26

尝试使用大写字母、小写字母、数字和特殊字符

function generatePassword($_len) {

    $_alphaSmall = 'abcdefghijklmnopqrstuvwxyz';            // small letters
    $_alphaCaps  = strtoupper($_alphaSmall);                // CAPITAL LETTERS
    $_numerics   = '1234567890';                            // numerics
    $_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|';   // Special Characters

    $_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars;   // Contains all characters
    $password = '';         // will contain the desired pass

    for($i = 0; $i < $_len; $i++) {                                 // Loop till the length mentioned
        $_rand = rand(0, strlen($_container) - 1);                  // Get Randomized Length
        $password .= substr($_container, $_rand, 1);                // returns part of the string [ high tensile strength ;) ] 
    }

    return $password;       // Returns the generated Pass
}

假设我们需要 10 位数字通行证

echo generatePassword(10);  

示例输出:

,IZCQ_IV\7

@wlqsfhT(d

1!8+1\4@uD

Try This with Capital Letters, Small Letters, Numeric(s) and Special Characters

function generatePassword($_len) {

    $_alphaSmall = 'abcdefghijklmnopqrstuvwxyz';            // small letters
    $_alphaCaps  = strtoupper($_alphaSmall);                // CAPITAL LETTERS
    $_numerics   = '1234567890';                            // numerics
    $_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|';   // Special Characters

    $_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars;   // Contains all characters
    $password = '';         // will contain the desired pass

    for($i = 0; $i < $_len; $i++) {                                 // Loop till the length mentioned
        $_rand = rand(0, strlen($_container) - 1);                  // Get Randomized Length
        $password .= substr($_container, $_rand, 1);                // returns part of the string [ high tensile strength ;) ] 
    }

    return $password;       // Returns the generated Pass
}

Let's Say we need 10 Digit Pass

echo generatePassword(10);  

Example Output(s) :

,IZCQ_IV\7

@wlqsfhT(d

1!8+1\4@uD

云柯 2024-11-16 02:20:26

使用这个简单的代码生成 12 长度的中等强密码

$password_string = '!@#$%*&abcdefghijklmnpqrstuwxyzABCDEFGHJKLMNPQRSTUWXYZ23456789';
$password = substr(str_shuffle($password_string), 0, 12);

Use this simple code for generate med-strong password 12 length

$password_string = '!@#$%*&abcdefghijklmnpqrstuwxyzABCDEFGHJKLMNPQRSTUWXYZ23456789';
$password = substr(str_shuffle($password_string), 0, 12);
洋洋洒洒 2024-11-16 02:20:26

这是我对选项列表的贡献。

此功能可确保满足密码策略。

  function password_generate($length=8, $min_lowercases=1, $min_uppercases=1, $min_numbers=1, $min_specials=0) {

    $lowercases = 'abcdefghijklmnopqrstuvwxyz';
    $uppercases = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $numbers = '0123456789';
    $specials = '!#%&/(){}[]+-';

    $absolutes = '';
    if ($min_lowercases && !is_bool($min_lowercases)) $absolutes .= substr(str_shuffle(str_repeat($lowercases, $min_lowercases)), 0, $min_lowercases);
    if ($min_uppercases && !is_bool($min_uppercases)) $absolutes .= substr(str_shuffle(str_repeat($uppercases, $min_uppercases)), 0, $min_uppercases);
    if ($min_numbers && !is_bool($min_numbers)) $absolutes .= substr(str_shuffle(str_repeat($numbers, $min_numbers)), 0, $min_numbers);
    if ($min_specials && !is_bool($min_specials)) $absolutes .= substr(str_shuffle(str_repeat($specials, $min_specials)), 0, $min_specials);

    $remaining = $length - strlen($absolutes);

    $characters = '';
    if ($min_lowercases !== false) $characters .= substr(str_shuffle(str_repeat($lowercases, $remaining)), 0, $remaining);
    if ($min_uppercases !== false) $characters .= substr(str_shuffle(str_repeat($uppercases, $remaining)), 0, $remaining);
    if ($min_numbers !== false) $characters .= substr(str_shuffle(str_repeat($numbers, $remaining)), 0, $remaining);
    if ($min_specials !== false) $characters .= substr(str_shuffle(str_repeat($specials, $remaining)), 0, $remaining);

    $password = str_shuffle($absolutes . substr($characters, 0, $remaining));

    return $password;
  }

$min_* 参数可以具有以下值:

  • 1-999 = 必需
  • true = 可选
  • false = 禁用

它可以按如下方式使用:

echo password_generate(8); // Outputs a random 8 characters long password

10 个字符的密码,每组至少有 2 个字符:

echo password_generate(10, 2, 2, 2, 2);

仅输出 6 个随机数

echo password_generate(6, false, false, true, false);

Here is my contribution to the list of options.

This function ensures that the password policy is met.

  function password_generate($length=8, $min_lowercases=1, $min_uppercases=1, $min_numbers=1, $min_specials=0) {

    $lowercases = 'abcdefghijklmnopqrstuvwxyz';
    $uppercases = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $numbers = '0123456789';
    $specials = '!#%&/(){}[]+-';

    $absolutes = '';
    if ($min_lowercases && !is_bool($min_lowercases)) $absolutes .= substr(str_shuffle(str_repeat($lowercases, $min_lowercases)), 0, $min_lowercases);
    if ($min_uppercases && !is_bool($min_uppercases)) $absolutes .= substr(str_shuffle(str_repeat($uppercases, $min_uppercases)), 0, $min_uppercases);
    if ($min_numbers && !is_bool($min_numbers)) $absolutes .= substr(str_shuffle(str_repeat($numbers, $min_numbers)), 0, $min_numbers);
    if ($min_specials && !is_bool($min_specials)) $absolutes .= substr(str_shuffle(str_repeat($specials, $min_specials)), 0, $min_specials);

    $remaining = $length - strlen($absolutes);

    $characters = '';
    if ($min_lowercases !== false) $characters .= substr(str_shuffle(str_repeat($lowercases, $remaining)), 0, $remaining);
    if ($min_uppercases !== false) $characters .= substr(str_shuffle(str_repeat($uppercases, $remaining)), 0, $remaining);
    if ($min_numbers !== false) $characters .= substr(str_shuffle(str_repeat($numbers, $remaining)), 0, $remaining);
    if ($min_specials !== false) $characters .= substr(str_shuffle(str_repeat($specials, $remaining)), 0, $remaining);

    $password = str_shuffle($absolutes . substr($characters, 0, $remaining));

    return $password;
  }

The $min_* parameters can have the following values:

  • 1-999 = required
  • true = optional
  • false = disabled

It can be used like the following:

echo password_generate(8); // Outputs a random 8 characters long password

A 10 character password with a minimum of 2 charcaters from each set:

echo password_generate(10, 2, 2, 2, 2);

Output 6 random numbers only

echo password_generate(6, false, false, true, false);
薄荷梦 2024-11-16 02:20:26

快一号。简单、干净、一致的格式(如果这是您想要的)

$pw = chr(mt_rand(97,122)).mt_rand(0,9).chr(mt_rand(97,122)).mt_rand(10,99).chr(mt_rand(97,122)).mt_rand(100,999);

Quick One. Simple, clean and consistent format if that is what you want

$pw = chr(mt_rand(97,122)).mt_rand(0,9).chr(mt_rand(97,122)).mt_rand(10,99).chr(mt_rand(97,122)).mt_rand(100,999);
女中豪杰 2024-11-16 02:20:26

这是基于本页上的另一个答案, https://stackoverflow.com/a/21498316/525649

此答案生成只是十六进制字符,0-9,af。对于看起来不像十六进制的内容,请尝试以下操作:

str_shuffle(
  rtrim(
    base64_encode(bin2hex(openssl_random_pseudo_bytes(5))),
    '='
  ). 
  strtoupper(bin2hex(openssl_random_pseudo_bytes(7))).
  bin2hex(openssl_random_pseudo_bytes(13))
)
  • base64_encode 返回更广泛的字母数字字符
  • rtrim 有时会删除末尾的 =

示例:

  • 32eFVfGDg891Be5e7293e54z1D23110M3ZU3FMjb30Z9a740Ej0jz4 05
  • 1b33654C0Eg201cfW0e6NA4b9614ze8D2FN49E12Y0zY557aUCb8
  • y67Q86ffd83G0z00M0Z152f7O2ADcY313gD7a774fc5FF069zdb5b7

这对于创建界面来说不是很好配置,但对于某些目的没关系。增加字符数以解决特殊字符的缺失问题。

This is based off another answer on this page, https://stackoverflow.com/a/21498316/525649

This answer generates just hex characters, 0-9,a-f. For something that doesn't look like hex, try this:

str_shuffle(
  rtrim(
    base64_encode(bin2hex(openssl_random_pseudo_bytes(5))),
    '='
  ). 
  strtoupper(bin2hex(openssl_random_pseudo_bytes(7))).
  bin2hex(openssl_random_pseudo_bytes(13))
)
  • base64_encode returns a wider spread of alphanumeric chars
  • rtrim removes the = sometimes at the end

Examples:

  • 32eFVfGDg891Be5e7293e54z1D23110M3ZU3FMjb30Z9a740Ej0jz4
  • b280R72b48eOm77a25YCj093DE5d9549Gc73Jg8TdD9Z0Nj4b98760
  • 051b33654C0Eg201cfW0e6NA4b9614ze8D2FN49E12Y0zY557aUCb8
  • y67Q86ffd83G0z00M0Z152f7O2ADcY313gD7a774fc5FF069zdb5b7

This isn't very configurable for creating an interface for users, but for some purposes that's okay. Increase the number of chars to account for the lack of special characters.

单挑你×的.吻 2024-11-16 02:20:26
  1. 创建一个文件,其中包含此代码。
  2. 像评论中那样称呼它。

    <前><代码>createPassword(10);
    * 返回$pwd;
    *
    */

    类密码{

    公共函数createPassword($length = 15) {
    $响应=[];
    $response['pwd'] = $this->generate($length);
    $response['hashPwd'] = $this->hashPwd( $response['pwd'] );
    返回$响应;
    }

    私有函数生成($length = 15) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(){}/?,><";
    返回 substr(str_shuffle($chars),0,$length);
    }

    私有函数 hashPwd($pwd) {
    返回哈希('sha256',$pwd);
    }

    }

    ?>

  1. Create a file with this code in it.
  2. Call it like in the comments.

    <?php 
    
    /**
    * @usage  :
    *       include_once($path . '/Password.php');
    *       $Password = new Password;
    *       $pwd = $Password->createPassword(10);
    *       return $pwd;
    * 
    */
    
    class Password {
    
        public function createPassword($length = 15) {
            $response = [];
            $response['pwd'] = $this->generate($length);
            $response['hashPwd'] = $this->hashPwd( $response['pwd'] );
            return $response;
        }
    
        private function generate($length = 15) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(){}/?,><";
            return substr(str_shuffle($chars),0,$length);
        }
    
        private function hashPwd($pwd) {
            return hash('sha256', $pwd);
        }
    
    }
    
    ?>
    
梦忆晨望 2024-11-16 02:20:26

我创建了一个更全面、更安全的密码脚本。这将创建两个大写字母、两个小写字母、两个数字和两个特殊字符的组合。共8个字符。

$char = [range('A','Z'),range('a','z'),range(0,9),['*','%','
,'#','@','!','+','?','.']];
$pw = '';
for($a = 0; $a < count($char); $a++)
{
    $randomkeys = array_rand($char[$a], 2);
    $pw .= $char[$a][$randomkeys[0]].$char[$a][$randomkeys[1]];
}
$userPassword = str_shuffle($pw);

I created a more comprehensive and secure password script. This will create a combination of two uppercase, two lowercase, two numbers and two special characters. Total 8 characters.

$char = [range('A','Z'),range('a','z'),range(0,9),['*','%','
,'#','@','!','+','?','.']];
$pw = '';
for($a = 0; $a < count($char); $a++)
{
    $randomkeys = array_rand($char[$a], 2);
    $pw .= $char[$a][$randomkeys[0]].$char[$a][$randomkeys[1]];
}
$userPassword = str_shuffle($pw);
白芷 2024-11-16 02:20:26

我的答案与上面的一些类似,但我删除了元音、数字 1 和 0、字母 i,j, I, l, O,o, Q, q, X,x,Y,y,W,w。原因是:第一个很容易混淆(例如 l 和 1,具体取决于字体),其余的(以 Q 开头)是因为它们在我的语言中不存在,所以它们对于我来说可能有点奇怪超级终端用户。字符串还是够长的。另外,我知道使用一些特殊标志是理想的,但它们也与某些最终用户相处不好。

function generatePassword($length = 8) {

$chars = '23456789bcdfhkmnprstvzBCDFHJKLMNPRSTVZ';
$shuffled = str_shuffle($chars);
$result = mb_substr($shuffled, 0, $length);

return $result;
}

另外,通过这种方式,我们可以避免重复相同的字母和数字(不包括匹配大小写)

My answer is similar to some of the above, but I removed vowels, numbers 1 and 0, letters i,j, I, l, O,o, Q, q, X,x,Y,y,W,w. The reason is: the first ones are easy to mix up (like l and 1, depending on the font) and the rest (starting with Q) is because they don't exist in my language, so they might be a bit odd for super-end users. The string of characters is still long enough. Also, I know it would be ideal to use some special signs, but they also don't get along with some end-users.

function generatePassword($length = 8) {

$chars = '23456789bcdfhkmnprstvzBCDFHJKLMNPRSTVZ';
$shuffled = str_shuffle($chars);
$result = mb_substr($shuffled, 0, $length);

return $result;
}

Also, in this way, we avoid repeating the same letters and digits (match case not included)

行至春深 2024-11-16 02:20:26

一个简单的代码应该像:

function generatePassword($len){
    $az = range("a","z");
    $AZ = range("A","Z");
    $num = range(0,9);
    $password = array_merge($az,$AZ,$num);
    return substr(str_shuffle(implode("",$password)),0, $len);
}
// testing 
$generate = range(8,32);
foreach($generate as $g){
    print "Len:{$g} = " . generatePassword($g)."\n";
}

输出:

Len:8 = G5uFhPKS
Len:9 = aU9x2NjvI
Len:10 = lJE9kxy3oD
Len:11 = tVh2CmpMdHW
Len:12 = ToXYHCPb58Ar
Len:13 = KIFVoLg5NdDzX
Len:14 = eFUabML28tXhf0
Len:15 = iegDCQcIMaxH0ST
Len:16 = sRvDmPo5IkaMqNO0
Len:17 = T5rwVDs6XGAqSU9KN
Len:18 = QwROWAfh1lpoCSaX0H
Len:19 = HP0trD4B9SQeUkNuAGV
Len:20 = P9Fdwqmu782ARHDiKGZM
Len:21 = 3Gxia9LPmCZM68dwe4YOf
Len:22 = ywFjuA2GDg0Oz8LVnCI94M
Len:23 = 16MiEVUgqPRueahlyvJfBz5
Len:24 = sPt0H9NSu5KrJTYeMXbOFgi7
Len:25 = QFKGTypaZlsMRnHPgNbVfIwxm
Len:26 = hbyJXtV81AEuMazS4GdFTINBUg
Len:27 = H3AiD95S4Z8xwMrz2L71GqUunaW
Len:28 = m8W2geIiO7Phc3H5Kyr1XCAs09Dv
Len:29 = MusNfYgOWnbrI62twRBvj38XEcDdi
Len:30 = VgNeILaRT2wvb4J7hzCMSHsquUBtnA
Len:31 = nhUvCxgOS94dsYjzBtcaTou1WIArMQP
Len:32 = AFSVQqCijuPMp0cGJNdDtzYX78erKB9w

A simple code should be like :

function generatePassword($len){
    $az = range("a","z");
    $AZ = range("A","Z");
    $num = range(0,9);
    $password = array_merge($az,$AZ,$num);
    return substr(str_shuffle(implode("",$password)),0, $len);
}
// testing 
$generate = range(8,32);
foreach($generate as $g){
    print "Len:{$g} = " . generatePassword($g)."\n";
}

output:

Len:8 = G5uFhPKS
Len:9 = aU9x2NjvI
Len:10 = lJE9kxy3oD
Len:11 = tVh2CmpMdHW
Len:12 = ToXYHCPb58Ar
Len:13 = KIFVoLg5NdDzX
Len:14 = eFUabML28tXhf0
Len:15 = iegDCQcIMaxH0ST
Len:16 = sRvDmPo5IkaMqNO0
Len:17 = T5rwVDs6XGAqSU9KN
Len:18 = QwROWAfh1lpoCSaX0H
Len:19 = HP0trD4B9SQeUkNuAGV
Len:20 = P9Fdwqmu782ARHDiKGZM
Len:21 = 3Gxia9LPmCZM68dwe4YOf
Len:22 = ywFjuA2GDg0Oz8LVnCI94M
Len:23 = 16MiEVUgqPRueahlyvJfBz5
Len:24 = sPt0H9NSu5KrJTYeMXbOFgi7
Len:25 = QFKGTypaZlsMRnHPgNbVfIwxm
Len:26 = hbyJXtV81AEuMazS4GdFTINBUg
Len:27 = H3AiD95S4Z8xwMrz2L71GqUunaW
Len:28 = m8W2geIiO7Phc3H5Kyr1XCAs09Dv
Len:29 = MusNfYgOWnbrI62twRBvj38XEcDdi
Len:30 = VgNeILaRT2wvb4J7hzCMSHsquUBtnA
Len:31 = nhUvCxgOS94dsYjzBtcaTou1WIArMQP
Len:32 = AFSVQqCijuPMp0cGJNdDtzYX78erKB9w
意中人 2024-11-16 02:20:26

生成长度为 8 的强密码,其中至少包含 1 个小写字母、1 个大写字母、1 个数字和 1 个特殊字符。您也可以更改代码中的长度。

function checkForCharacterCondition($string) {
    return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}

$j = 1;

function generate_pass() {
    global $j;
    $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
    $pass = '';
    $length = 8;
    $max = mb_strlen($allowedCharacters, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pass .= $allowedCharacters[random_int(0, $max)];
    }

    if (checkForCharacterCondition($pass)){
        return '<br><strong>Selected password: </strong>'.$pass;
    }else{
        echo 'Iteration '.$j.':  <strong>'.$pass.'</strong>  Rejected<br>';
        $j++;
        return generate_pass();
    }

}

echo generate_pass();

Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.

function checkForCharacterCondition($string) {
    return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}

$j = 1;

function generate_pass() {
    global $j;
    $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
    $pass = '';
    $length = 8;
    $max = mb_strlen($allowedCharacters, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pass .= $allowedCharacters[random_int(0, $max)];
    }

    if (checkForCharacterCondition($pass)){
        return '<br><strong>Selected password: </strong>'.$pass;
    }else{
        echo 'Iteration '.$j.':  <strong>'.$pass.'</strong>  Rejected<br>';
        $j++;
        return generate_pass();
    }

}

echo generate_pass();
皇甫轩 2024-11-16 02:20:26
//define a function. It is only 3 lines!   
function generateRandomPassword($length = 5){
    $chars = "0123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return substr(str_shuffle($chars),0,$length);
}

//usage
echo generateRandomPassword(5); //random password legth: 5
echo generateRandomPassword(6); //random password legth: 6
echo generateRandomPassword(7); //random password legth: 7
//define a function. It is only 3 lines!   
function generateRandomPassword($length = 5){
    $chars = "0123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return substr(str_shuffle($chars),0,$length);
}

//usage
echo generateRandomPassword(5); //random password legth: 5
echo generateRandomPassword(6); //random password legth: 6
echo generateRandomPassword(7); //random password legth: 7
清君侧 2024-11-16 02:20:26

这是我对随机纯密码生成助手的看法。

它确保密码包含数字、大小写字母以及至少 3 个特殊字符。

密码长度在 11 到 30 之间。

function plainPassword(): string
{
    $numbers = array_rand(range(0, 9), rand(3, 9));
    $uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
    $lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
    $special = array_rand(array_flip(['@', '#', '
, '!', '%', '*', '?', '&']), rand(3, 5));

    $password = array_merge(
        $numbers,
        $uppercase,
        $lowercase,
        $special
    );

    shuffle($password);

    return implode($password);
}

Here's my take at random plain password generation helper.

It ensures that password has numbers, upper and lower case letters as well as a minimum of 3 special characters.

Length of the password will be between 11 and 30.

function plainPassword(): string
{
    $numbers = array_rand(range(0, 9), rand(3, 9));
    $uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
    $lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
    $special = array_rand(array_flip(['@', '#', '
, '!', '%', '*', '?', '&']), rand(3, 5));

    $password = array_merge(
        $numbers,
        $uppercase,
        $lowercase,
        $special
    );

    shuffle($password);

    return implode($password);
}
晨曦÷微暖 2024-11-16 02:20:26

生成随机密码字符串

function generate_randompassword($passlength = 8){
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#%^*>\$@?/[]=+';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < $passlength; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

Generate random password string

function generate_randompassword($passlength = 8){
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#%^*>\$@?/[]=+';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < $passlength; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}
手心的温暖 2024-11-16 02:20:26

在我的例子中,我使用 uniqid();它根据当前时间(以微秒为单位)获取唯一的前缀值。这样就很难重复这个值,否则如果需要加密密码,也可以使用password_hash()。

按照示例:

public function randowPassWord() : string {
 return password_hash(uniqid(), PASSWORD_DEFAULT);
}

或者只使用 uniqid();

public function randowPassWord() : string {
  return uniqid();
}

有用的链接:

https://www.php.net/manual/en /function.password-hash.php

https://www.php.net/manual/pt_BR/function.uniqid.php

In my case I use uniqid(); it gets a unique prefixed value based on the current time in microseconds. In this way it is very difficult to repeat this value, otherwise you can also use password_hash(), if you need to encrypt the password.

Follow the examples:

public function randowPassWord() : string {
 return password_hash(uniqid(), PASSWORD_DEFAULT);
}

Or just use uniqid();

public function randowPassWord() : string {
  return uniqid();
}

Useful links:

https://www.php.net/manual/en/function.password-hash.php

https://www.php.net/manual/pt_BR/function.uniqid.php

private function generatePassword(): string
{
    return Arr::join(
        Arr::shuffle(
            Arr::collapse([
                Arr::random(range(0, 9), 3),
                Arr::random(range('A', 'Z'), 3),
                Arr::random(range('a', 'z'), 3),
                Arr::random(['@', '#', '
, '!', '%', '*', '?', '&'], 3)
            ])
        )
        , ''
    );
}
private function generatePassword(): string
{
    return Arr::join(
        Arr::shuffle(
            Arr::collapse([
                Arr::random(range(0, 9), 3),
                Arr::random(range('A', 'Z'), 3),
                Arr::random(range('a', 'z'), 3),
                Arr::random(['@', '#', '
, '!', '%', '*', '?', '&'], 3)
            ])
        )
        , ''
    );
}
木緿 2024-11-16 02:20:26

该函数会根据参数中的规则生成密码

function random_password( $length = 8, $characters = true, $numbers = true, $case_sensitive = true, $hash = true ) {

    $password = '';

    if($characters)
    {
        $charLength = $length;
        if($numbers) $charLength-=2;
        if($case_sensitive) $charLength-=2;
        if($hash) $charLength-=2;
        $chars = "abcdefghijklmnopqrstuvwxyz";
        $password.= substr( str_shuffle( $chars ), 0, $charLength );
    }

    if($numbers)
    {
        $numbersLength = $length;
        if($characters) $numbersLength-=2;
        if($case_sensitive) $numbersLength-=2;
        if($hash) $numbersLength-=2;
        $chars = "0123456789";
        $password.= substr( str_shuffle( $chars ), 0, $numbersLength );
    }

    if($case_sensitive)
    {
        $UpperCaseLength = $length;
        if($characters) $UpperCaseLength-=2;
        if($numbers) $UpperCaseLength-=2;
        if($hash) $UpperCaseLength-=2;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $password.= substr( str_shuffle( $chars ), 0, $UpperCaseLength );
    }

    if($hash)
    {
        $hashLength = $length;
        if($characters) $hashLength-=2;
        if($numbers) $hashLength-=2;
        if($case_sensitive) $hashLength-=2;
        $chars = "!@#$%^&*()_-=+;:,.?";
        $password.= substr( str_shuffle( $chars ), 0, $hashLength );
    }

    $password = str_shuffle( $password );
    return $password;
}

This function will generate a password based on the rules in parameters

function random_password( $length = 8, $characters = true, $numbers = true, $case_sensitive = true, $hash = true ) {

    $password = '';

    if($characters)
    {
        $charLength = $length;
        if($numbers) $charLength-=2;
        if($case_sensitive) $charLength-=2;
        if($hash) $charLength-=2;
        $chars = "abcdefghijklmnopqrstuvwxyz";
        $password.= substr( str_shuffle( $chars ), 0, $charLength );
    }

    if($numbers)
    {
        $numbersLength = $length;
        if($characters) $numbersLength-=2;
        if($case_sensitive) $numbersLength-=2;
        if($hash) $numbersLength-=2;
        $chars = "0123456789";
        $password.= substr( str_shuffle( $chars ), 0, $numbersLength );
    }

    if($case_sensitive)
    {
        $UpperCaseLength = $length;
        if($characters) $UpperCaseLength-=2;
        if($numbers) $UpperCaseLength-=2;
        if($hash) $UpperCaseLength-=2;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $password.= substr( str_shuffle( $chars ), 0, $UpperCaseLength );
    }

    if($hash)
    {
        $hashLength = $length;
        if($characters) $hashLength-=2;
        if($numbers) $hashLength-=2;
        if($case_sensitive) $hashLength-=2;
        $chars = "!@#$%^&*()_-=+;:,.?";
        $password.= substr( str_shuffle( $chars ), 0, $hashLength );
    }

    $password = str_shuffle( $password );
    return $password;
}
坚持沉默 2024-11-16 02:20:26

这是我的密码助手

class PasswordHelper
{
    /**
    * generate a secured random password
    */
    public static function generatePassword(
        int $lowerCaseCount=8, 
        int $upperCaseCount=8, 
        int $numberCount=8, 
        int $specialCount=4
    ): string
    {
        $lowerCase  = 'abcdefghijklmnopqrstuvwxyz';
        $upperCase  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number     = '0123456789';
        $special    = '!@#$%^&*';

        $password = self::getRandom($lowerCase, $lowerCaseCount);
        $password .= self::getRandom($upperCase, $upperCaseCount);
        $password .= self::getRandom($number, $numberCount);
        $password .= self::getRandom($special, $specialCount);

        return str_shuffle($password);
    }

    /**
     * get a random string from a set of characters
     */
    public static function getRandom($set, $length): string
    {
        $rand = '';
        $setLength = strlen($set);

        for ($i = 0; $i < $length; $i++)
        {
            $rand .= $set[random_int(0, $setLength - 1)];
        }

        return $rand;
    }
}

用法:

PasswordHelper::generatePassword()PasswordHelper::generatePassword(2,4,5,3)

Here is my password helper

class PasswordHelper
{
    /**
    * generate a secured random password
    */
    public static function generatePassword(
        int $lowerCaseCount=8, 
        int $upperCaseCount=8, 
        int $numberCount=8, 
        int $specialCount=4
    ): string
    {
        $lowerCase  = 'abcdefghijklmnopqrstuvwxyz';
        $upperCase  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number     = '0123456789';
        $special    = '!@#$%^&*';

        $password = self::getRandom($lowerCase, $lowerCaseCount);
        $password .= self::getRandom($upperCase, $upperCaseCount);
        $password .= self::getRandom($number, $numberCount);
        $password .= self::getRandom($special, $specialCount);

        return str_shuffle($password);
    }

    /**
     * get a random string from a set of characters
     */
    public static function getRandom($set, $length): string
    {
        $rand = '';
        $setLength = strlen($set);

        for ($i = 0; $i < $length; $i++)
        {
            $rand .= $set[random_int(0, $setLength - 1)];
        }

        return $rand;
    }
}

usage:

PasswordHelper::generatePassword() or PasswordHelper::generatePassword(2,4,5,3)

感性不性感 2024-11-16 02:20:26

有一个简短的解决方案(php 8.1):

$dict = array_merge(
    ...array_map(
        fn(array $d): array => range(ord($d[0]), ord($d[1])),
        [["0", "9"], ["a", "z"], ["A", "Z"]]
    )
); 

$f = fn (int $len): string =>
    join(
        "",
        array_map(
            fn (): string => chr($dict[random_int(0, count($dict) - 1)]),
            range(0, $len)
        )
    ); 

echo $f(12) . PHP_EOL;

一行 bash 脚本:

php -r '$dict = array_merge(...array_map(fn(array $d): array => range(ord($d) [0]), ord($d[1])), [["0", "9"], ["a", "z"], ["A", "Z"]] )); $f = fn (int $len): 字符串 => join("", array_map(fn (): string => chr($dict[random_int(0, count($dict) - 1)]), range(0, $len) ));回声 $f(12) 。 PHP_EOL;'

这是来自 https://stackoverflow.com/a/41077923/5599052

There is one short solution (php 8.1):

$dict = array_merge(
    ...array_map(
        fn(array $d): array => range(ord($d[0]), ord($d[1])),
        [["0", "9"], ["a", "z"], ["A", "Z"]]
    )
); 

$f = fn (int $len): string =>
    join(
        "",
        array_map(
            fn (): string => chr($dict[random_int(0, count($dict) - 1)]),
            range(0, $len)
        )
    ); 

echo $f(12) . PHP_EOL;

one-line bash script:

php -r '$dict = array_merge(...array_map(fn(array $d): array => range(ord($d[0]), ord($d[1])), [["0", "9"], ["a", "z"], ["A", "Z"]] )); $f = fn (int $len): string => join("", array_map(fn (): string => chr($dict[random_int(0, count($dict) - 1)]), range(0, $len) )); echo $f(12) . PHP_EOL;'

This is developed idea from https://stackoverflow.com/a/41077923/5599052

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文