Random password generation with conditions
I'm working on a random password generator to create passwords that meet certain conditions including, but not necessarily limited to:
- minimum length: has to contain at least 8 characters
- l开发者_如何学Cower case letters: has to contain lower case letters (chosen from a set to avoid problems of having characters that can be mistaken as numbers)
- upper case letters: has to contain upper case letters (again, chosen from a set)
- digits: has to contain numbers
What would be the best algorithmic approach to ensure that the generated password meets all these?
I'm not looking for a complete solution, I only need a few good ideas and guidelines.
1) randomly generate number L which will be the exact length of your password. Namely, generate is so that it is greater than 8
2) randomly generate a number LL which will be the number of lowercase letters. LC must be in range [1..L-2]
3) randomly generate number LU for uppercase. Must be in range [1..L-LL-1]
4) LD = L-LL-LU number of uppercase digits
5) randomly generate LL lowercase letters, LU uppercase letters, and LD digits and keep them in a list(array)
6) Shuffle the array randomly
hth
- create a character array containing a - z, A - Z, 0 - 9 (minus any characters that might be confusing per the question)
- concatenate 8 randomly chosen characters from the array
- test the result to see if it satisfies the requirements
- if the requirements are not satisfied, start over
The algorithm should usually succeed on the first few iterations, and saves you from having to implement a shuffle algorithm.
There is an alternative to the precise construction proposed by Armen. If you're conditions can be met with high probability then:
- get an infinite length random string (a stream)
- lazily filter for the acceptable characters (ex: upper case || lower case || digit)
- step a window of the desired length across the stream, accept when the window properties are OK.
In a lazy language this is about 6 lines of non-boilerplate code and doesn't require any shuffling.
EDIT: Yes, step a window as in the comments, not slide a window. Thanks!
精彩评论