Random String/Password Generation in C#


I'm guessing that someone out there has been in my position at some point in time... Basically I needed a password generator for a web site that I'm working on. I've seen a number of password generators out there and to be honest, I'm not a big fan of most of them. At the same time I couldn't use the default membership providers (long story as to why not). So basically I was stuck finding a way to generate my own random passwords (not to mention my own membership provider).

It's not a difficult task mind you, just annoying. That being said, I came up with the following class:

    public class Random:System.Random
    {
        public Random()
            : base()
        {
        }

        public Random(int Seed)
            : base(Seed)
        {
        }

        public string NextString(int Length)
        {
            if(Length<1)
                return "";
            StringBuilder TempBuilder=new StringBuilder();
            while(TempBuilder.Length<Length)
            {
                TempBuilder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(94*NextDouble()+32))));
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length,string AllowedCharacters)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer=new Regex(AllowedCharacters);
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if(Comparer.IsMatch(TempValue))
                    TempBuilder.Append(TempValue);
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length, string AllowedCharacters,int NumberOfNonAlphaNumericsAllowed)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer = new Regex(AllowedCharacters);
            Regex AlphaNumbericComparer=new Regex("[0-9a-zA-z]");
            int Counter = 0;
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if (Comparer.IsMatch(TempValue))
                {
                    if (!AlphaNumbericComparer.IsMatch(TempValue) && NumberOfNonAlphaNumericsAllowed > Counter)
                    {
                        TempBuilder.Append(TempValue);
                        ++Counter;
                    }
                    else if (AlphaNumbericComparer.IsMatch(TempValue))
                    {
                        TempBuilder.Append(TempValue);
                    }
                }
            }
            return TempBuilder.ToString();
        }
    }

This class has three functions that it adds to the Random classes normal ones (NextDouble, etc.). The one that is probably of most interest is going to be the last one. That function takes in the length of the string that you want, a regular expression stating what characters are allowed, and the number of non alpha numeric characters. So for instance calling the function with this:

NextString(10,"[0-9a-zA-Z_]",1);

That would create a random string of 10 characters that contained letters, numbers, and up to one underscore. The other functions are similar but with less control. For instance the one that just takes the length will use all characters on the ASCII table from 32 (space) up to 126 (~). But you can use this for quite a few items, passwords, testing, blog post generation when you're extremely bored and lazy... The list is rather endless... Anyway, I hope this helps someone out, so try out the code, leave feedback, and happy coding.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by James Craig on Monday, November 24, 2008 12:27 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Recent comments

None

Calendar

<<  January 2009  >>
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

Sponsors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009