Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment

Locations of visitors to this page

Latest Articles

Move to top
Ways of generating random password or string
Posted By Sarin on Oct 05, 2012     RSS Feeds     Latest Hinduism news

In previous article, we saw how to generate unique random numbers. In this article, let us see How to generate random string or more precisely how to generate password:
The simplest way would be to call inbuilt Path GetRandomFileName static method which returns a random string:

String ran = System.IO.Path.GetRandomFileName().Replace(".", string.Empty);
This might not fulfill your requirement because the generated random string would be lowercase; of uncontrolled length and with no special characters.
Another simple way would be to use ASP.Net Membership type:
String ran = System.Web.Security.Membership.GeneratePassword(10, 0);
Second parameter to this method let you specify the number of special characters you want to have in your generated string. But for some reason, even if zero is passed to this method, many special characters like @, %, $, (, [, {is still included in the generated string. It is not always that want special characters in the generated random string. Let us see some other ways of generating random string although it would not be simpler as the above methods.
Now that we have a way to generate random numbers, let's get back to strings. I'm going to post the entire method here and then explain it in details:
  public static string GetRandomPassword(int length, Random ran)
            string[] array = new string[54]
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) sb.Append(array[ran.Next(54)]);
            return sb.ToString();
Call above function as  
Random ran = new Random();
string password = GetRandomPassword(10, ran);
My approach is very simple. I have declared an array with all characters I would like to have in the generated password. You can add special characters to this array. Next, I append random characters from this array to string builder till its length is equal to input parameter ‘length’.
Same thing can be achieved using Linq query as well
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".ToArray();
            password = Enumerable.Range(0, PassLength)
                                      new StringBuilder(),
                                      (sb, n) => sb.Append((chars[ran.Next(chars.Length)])),
                                      sb => sb.ToString());

Above method generate random password by aggregating random chars into a string builder.
Replace passlength with integer value representing length of your password
Another way to generate random string is by using GUID.
Simplest case would be to retrieve the first eight characters of GUID as a password
Guid.NewGuid().ToString().Substring(0, 8);
Out of 1, 00,000 iterations, I got only one duplicate password. So, for a fairly small application, one can use the above technique to retrieve password since the dash in GUID comes after the first 8 characters and coder can check for duplicates by checking if the generated password already exists in the database. If password exists, then retrieve again by using new GUID.

If you want to eliminate the chances of duplicates, then use the below method
public  string  GenerateRandomString(int stringLength)

One can apply his own logic of generating random password. For Ex: one can use the below method to derive the random password by taking first parameter as length of string and second parameter to define case of string
   private static string RandomString(int size, bool lowerCase)
            StringBuilder sb = new StringBuilder();
            Random rand = new Random();
            char chr;
            for (int i = 0; i < size; i++)
          chr = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rand.NextDouble() + 65)));
            if (lowerCase)
                return sb.ToString().ToLower();
            return sb.ToString();
One can use the combination of random numbers and random string to generate random password. For Example, following code generates a password of 10 alphabets with first four letters lowercase, next four letters numbers, and last two letters as uppercase.
   public static string GetPassword()
            StringBuilder builder = new StringBuilder();
            Random rand = new Random();
            builder.Append(RandomString(4, true));
            builder.Append(rand.Next(1000, 9999));
            builder.Append(RandomString(2, false));
            return builder.ToString();
One of the methods I have used to generate a random password for user registration.
public2 3string2 Generate_Password4 ()2

Last and the best method to derive the random password would be to use inbuilt cryptography class as shown below
Using System.Security.Cryptography;
public class GenerateKey
        public static string GetKey(int maxSize)
            char[] chars = new char[62];
            chars ="!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[maxSize];
            RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider();
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
                result.Append(chars[b % (chars.Length)]);
            return result.ToString();
Generated password would look like  

In this method, I create a byte array with random byte values. This random byte values is then used to generate a char which is then appended to string builder. After all the chars are appended to string builder, we get the new password.
These are just a few ways of generating password. One can create his own way of generating password which might be better and faster than all the above listed methods. But I hope this article proves to be a good start on for your requirement of generating random password.

Dowload Source Code
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(, Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Capitalise first character of every word
Parse comma separated input string in SQL
Generating unique random numbers and date
Get All Tables in a Database
SQL-Removing numbers in a string
Create property class of database table
Advanced Datetime Format for string
Different types of File Write Operations
Advanced Strings Format for numbers
When to use optional parameters of creating database statement

Post Comment