RSS

Generate Random Password

12 Aug

Enhancing the same password generation logic so that it would be useful for generating random password using C# code.

Client Side (RandPwd.aspx)

<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”rndpwd” runat=”server” Text=”Generate Pwd” onclick=”rndpwd_Click” />
<br />
<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>
</div>
</form>

Server Side

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

        for (int i = 0; i < length; i++)
        {
            int x = 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;
    }

Display Result of Pwd

protected void rndpwd_Click(object sender, EventArgs e)
    {
        Label1.Text=GetRandomPassword(Convert.ToInt32(TextBox1.Text));
    }

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.
Advertisements
 
Leave a comment

Posted by on August 12, 2011 in ASP Dot Net C#

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: