简体   繁体   English

如何在PHP中生成(某种程度上)安全密码?

[英]How To Generate (Somewhat) Secure Passwords in PHP?

I'm trying to come up with a function that can generate random passwords, that must meet the following requirements: 我试图提供一个可以生成随机密码的函数,该函数必须满足以下要求:

  • Between 8 & 14 characters 8至14个字符
  • Contain a least one of the following: lowercase letter, uppercase letter, punctuation, and number 包含以下至少一项:小写字母,大写字母,标点和数字

what would be the best way about going about this, such that the function can generate every possible password that meets said requirements? 最好的方法是什么,以便该功能可以生成满足上述要求的所有可能的密码?

  1. Generate a lowercase letter, uppercase letter, punctuation symbol and number, so you now have 4 characters. 生成小写字母,大写字母,标点符号和数字,因此您现在拥有4个字符。
  2. Generate 4-10 random characters from the entire set of above. 从上面的整个集合中生成4-10个随机字符。
  3. Shuffle the resulting string. 随机排列结果字符串。 In PHP you can use str_shuffle . 在PHP中,您可以使用str_shuffle

However, it should be noted that if you're generating random characters, forcing every password to have at least one number/punctuation etc is not really any more secure. 但是,应该注意的是,如果要生成随机字符,则强制每个密码至少具有一个数字/标点符号等并不是真正安全。 In fact, you could say it's less secure since it actually limits your password choices. 实际上,您可以说它不太安全,因为它实际上限制了您的密码选择。

There are many examples on Google of a "PHP Password Generator" (that include source). Google上有许多“ PHP密码生成器” (包括源代码)的示例。 Several of them have the ability to specify minimum requirements from the character classes that you mention. 其中有几个功能可以从您提到的字符类中指定最低要求。

Most of these rely on the rand() function. 其中大多数依赖rand()函数。 This has some security risks, but those may be acceptable to you. 这有一些安全风险,但是您可能会接受。 You can also replace this with the mt_rand() function for better randomness. 您也可以使用mt_rand()函数替换它,以获得更好的随机性。

If you really need to get a good random source, you'll need to lean on the OS (ie /dev/random in linux or the Utilities object in Windows). 如果您确实需要获得良好的随机源,则需要依靠操作系统(即Linux中的/dev/random或Windows中的Utilities对象)。

somewhat lazy approach: 有点偷懒的方法:

Generate a random number between 8 and 14 生成8到14之间的随机数
generate a completely random string of characters that is that long 生成一个完全随机的字符串,那么长
Check it against a regular expression that defines the lowercase/uppercase/etc requirement If it fails, try again. 根据定义了小写/大写/等要求的正则表达式对其进行检查。如果失败,请重试。

Should be pretty simple with sha1. 使用sha1应该非常简单。 Something like this and just chop it to correct length, pick randomly for uppercasing, insert random punctuation: 像这样,然后将其切成正确的长度,随机挑选大写字母,插入随机标点符号即可:

sha1(microtime() . rand(0,100))

I should point out I saw a really smart approach to this kind of password generation somewhere which was probably better than this, but can't recall where it was. 我应该指出,我在某处看到了一种非常聪明的方法来生成这种密码,这种方法可能比这更好,但是却不记得在哪里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM