Ways of generating random password or string
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]
{
"a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z","0","2","3","4","5","6","8","9","A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"
};
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)
.Aggregate(
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)));
sb.Append(chr);
}
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.