Generate random password in C#

Mar 28, 2006

I recently had to make a method that creates a random generated password in C#. So, I looked at the web for such a function and I found this one. It was really simple and short and just what I was looking for. But, there is always a but, it didn't work. So I modified it a bit, and it now looks like this and it works.

private static string CreateRandomPassword(int passwordLength)
{
 string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
 char[] chars = new char[passwordLength];
 Random rd = new Random();

 for (int i = 0; i < passwordLength; i++)
 {
  chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
 }

 return new string(chars);
}

It's that simple.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (4) -

 wishy
wishy
3/25/2007 12:53:07 PM #

it's great! can u explain every line? i want to understand every code. because i don't want to just copy it! i want to learn if u don't mind. tnx!

Tahir
Tahir Malaysia
4/9/2008 8:05:02 AM #

Thanks...it helped

Bryan Canonica
Bryan Canonica United States
8/11/2008 5:12:20 PM #

This code can give you back strings with curse words in them.  I would suggest using the code above modified a bit to alternate numerals and letters.  

Bryan Canonica
Bryan Canonica United States
8/11/2008 5:25:17 PM #

//Something like this builds on Mads Excellent code.  

public static string GenerateRandomString(int length)
        {
            //Removed O, o, 0, l, 1
            string allowedLetterChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
            string allowedNumberChars = "23456789";
            char[] chars = new char[length];
            Random rd = new Random();

            bool useLetter =  true;
            for (int i = 0; i < length; i++)
            {
                if (useLetter)
                {
                    chars[i] = allowedLetterChars[rd.Next(0, allowedLetterChars.Length)];
                    useLetter = false;
                }
                else
                {
                    chars[i] = allowedNumberChars[rd.Next(0, allowedNumberChars.Length)];
                    useLetter = true;
                }

            }

            return new string(chars);
        }

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.