Search code examples
c#passwordsgenerator

Code for password generator


I'm working on a C# project where I need to generate random passwords.

Can anyone provide some code or a high-level approach for password generation?

It should be possible to specify the following:

  1. Minimum password length
  2. Maximum password length
  3. Valid uppercase characters
  4. Minimum number of uppercase chars
  5. Valid lowercase chars
  6. Minimum number of lowercase chars
  7. Valid numeric chars
  8. Minimum number of numeric chars
  9. Valid alfanum chars.
  10. Minimum number of alfanum chars

Solution

  • I wrote a simple Data generation library ages ago to mock up some data we needed, you could take a look at that to get some ideas. You provide it with a pattern which you want to generate and it will create random data to match that pattern.

    The pattern is as follows:

    • * - An upper-case or lower-case letter or number.
    • L - An upper-case Letter.
    • l - A lower-case letter.
    • V - An upper-case Vowel.
    • v - A lower-case vowel.
    • C - An upper-case Consonant.
    • c - A lower-case consonant.
    • X - Any number, 0-9.
    • x - Any number, 1-9.

    Its not exactly what you are looking for but you should be able to modify it to suit your needs.

    This is the main logic
    EDIT: Reading through your requirements again I think you should be able to alter my code to get it to work. You would need to create a pattern that matches the minimum character/number requirements for a valid password, add logic to vary the length of the generated password by adding in random characters, and perhaps add some random sort logic at the end to mix the characters up so that they are not always in the same pattern.

    EDIT(2): Moved the code to GitHub, updated links.

    EDIT(3): Linked to main Github repo instead.