tags:

views:

98

answers:

4

I'm trying to come up with a function that can generate random passwords, that must meet the following requirements:

  • Between 8 & 14 characters
  • 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?

A: 

somewhat lazy approach:

Generate a random number between 8 and 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.

Brian Schroth
A: 

Should be pretty simple with 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.

Jani Hartikainen
+5  A: 
  1. Generate a lowercase letter, uppercase letter, punctuation symbol and number, so you now have 4 characters.
  2. Generate 4-10 random characters from the entire set of above.
  3. Shuffle the resulting string. In PHP you can use 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.

DisgruntledGoat
Good point on "limits password choices" by forcing a policy at this level. Password policies are usually to prevent people from choosing obvious things like 'password', not something a truly random password generator would do. +1
jheddings
exactly. The reason for this is to have passwords that will comply with anothers systems rules, which I have no control over. Like I said, I don't expect these to be super-secure, I just need something that I can use for resetting passwords when nessecary.
GSto
+1  A: 

There are many examples on Google of a "PHP Password Generator" (that include source). 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. 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.

If you really need to get a good random source, you'll need to lean on the OS (i.e. /dev/random in linux or the Utilities object in Windows).

jheddings