Wabbitseason
Wabbitseason

Reputation: 5691

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:

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.

Upvotes: 5

Views: 9540

Answers (3)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

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!

Upvotes: 1

dana
dana

Reputation: 18155

  • 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.

Upvotes: 4

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

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

Upvotes: 5

Related Questions