Asp.net: Generate random password

In this article I am going to explain how to generate random password in asp.net using C# and VB.net.

Implementation:

HTML Markup:
  <fieldset style="width:25%">
    <legend>Generate Random Password</legend>
    <table>
    <tr><td>Enter length :</td><td><asp:TextBox ID="txtlength" runat="server"></asp:TextBox></td></tr>
    <tr><td></td><td></td></tr>
    <tr><td></td><td><asp:Button ID="btnsubmit" runat="server" Text="Generate" /></td></tr>
    <tr><td colspan="2"><asp:Label ID="lbloutput" runat="server"></asp:Label></td></tr>
    </table>       
    </fieldset>


Create a method to Generate random password
Create a method to generate the alphanumeric random password.

C# code:
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        GenerateRandomPassword (Convert.ToInt32(txtlength.Text));
    }
    private void GenerateRandomPassword (int length)
    {
        try
        {
            string numbers = "0123456789";
            string LargeAplhabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string SmallAplhabets = "abcdefghijklmnopqrstuvwxyz";
            string allowedChars = numbers + LargeAplhabets + SmallAplhabets;

            Random objrandom = new Random();
            char[] chars = new char[length];

            for (int i = 0; i < length; i++)
            {
                chars[i] = allowedChars[Convert.ToInt32((allowedChars.Length - 1) * objrandom.NextDouble())];
            }
            string otp = new string(chars);
            lbloutput.Text = otp;
        }
        catch (Exception ex)
        {
        }
    }

VB.net code
Protected Sub btnsubmit_Click(sender As Object, e As System.EventArgs) Handles btnsubmit.Click
        GenerateRandomPassword (Convert.ToInt32(txtlength.Text))
    End Sub
    Private Sub GenerateRandomPassword(length As Integer)
        Try
            Dim numbers As String = "0123456789"
            Dim LargeAplhabets As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            Dim SmallAplhabets As String = "abcdefghijklmnopqrstuvwxyz"
            Dim allowedChars As String = Convert.ToString(numbers & LargeAplhabets) & SmallAplhabets
            Dim objrandom As New Random()
            Dim chars As Char() = New Char(length - 1) {}
            For i As Integer = 0 To length - 1
                chars(i) = allowedChars(Convert.ToInt32((allowedChars.Length - 1) * objrandom.NextDouble()))
            Next
            Dim otp As New String(chars)
            lbloutput.Text = otp
        Catch ex As Exception
        End Try
    End Sub 


Post a Comment

0 Comments