Generating Random Passwords with ASP. NET and C#


Generating random passwords can increase the security of a website by taking the process out of the hands of the user, or simply providing an alternative, and thus reducing the chance of easily-guessable passwords being used. This tutorial shows a simple method of creating a random password.

Generating random Password is the another way of secure login. This help to increase the security.

First, we create the aspx page and use the following code in the page :

<form id="form1" runat="server">
<div>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Generate Password" OnClick="Button1_Click" />
    <br />
    <br />
    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True"
        Font-Names="Arial"></asp:Label>
</div>
</form>

The simple method is shown below. This is Code behind the page aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Design; 

public
partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public static string CreateRandomPassword(int PasswordLength)
    { 
        string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
         return new string(chars);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
         Label1.Text =  CreateRandomPassword(8);
    }
}

In the above application we generate the random string that is useful for the registration form. In this method we generate the random string having numeric value, upper case and lower case alphabets.

OUTPUT

string-generate.jpg

Now when we click on Generate Password button than we immediately get the random string.

Up Next
    Ebook Download
    View all
    Learn
    View all