Random Password Generation Using C# | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Random Password Generation Using C#

Saturday


Generating Random Password Using C#:
                                                              The following method would be useful for generating random password using C#. You just give length of the password as input and get the random password.

Code:
   public static string GenerateRandomPassword(int length)
    {
        
char[] chars "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
        string 
password = string.Empty;
        
Random random = new Random();

        for 
(int 0i < lengthi++)
        {
            
int random.Next(1,chars.Length);
            
//Don't Allow Repetation of Characters
            
if (!password.Contains(chars.GetValue(x).ToString()))
                password +
chars.GetValue(x);
            else
                
i--;
        
}
        
return password;
    
}
Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.

2 comments:

Anonymous said...

If you disallow repetition of characters then you reduce the randomness of the password.

For example if I know the first N characters of the password then the N+1 th character is easier to guess than the first one.

Prince said...

Hai friend,
Thanks for your valuable comment. I don't think like you because this code is just enough for my client's requirement.
Another obvious solution is you can remove the if condition which don't allow repeatation of chars in password which can resolve your problem.

Post a Comment

Share your thoughts here...

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets