HI WELCOME TO KANSIRIS

GENERATE RANDOM UNIQUE ALPHANUMERIC ONE TIME PASSWORD (OTP) IN ASP.NET C#,VB

Leave a Comment
Introduction: In this article I am going to share how to generate or create random unique alphanumeric one time password (OTP) in Asp.Net using both C# and VB.

Generate Random Unique Alphanumeric One Time Password (OTP) in Asp.Net C#,VB
 Description: Nowadays  one time password(OTP) system is widely used by banks and other firms to authenticate users while making online transactions and other similar activities. Here I have created a function to generate OTP which is combination of numbers, lower and uppercase letters and special characters or symbols. 

I have added only few special characters while generating OTP but you can add as many as special characters as required to make it more unique. It generates the OTP of the length we specify. E.g. if we pass 10 from the textbox, it will generate OTP of length 10. OTP can be generated of any length as per requirement. Generated OTP can be sent through Email or SMS to user for authentication.


Implementation: Let’s create a sample web page for demonstration purpose

HTML Source:

Enter Number of Characters:
            <asp:TextBox ID="txtOTP" runat="server" />
                    <asp:Button ID="btnGenerateOTP" Text="Generate" runat="server"
                        OnClick="btnGenerateOTP_Click" /><br />
                    <asp:Label ID="lblOTP" runat="server" ForeColor="blue" />

Asp.Net C# Code to generate One Time Password(OTP)

protected void btnGenerateOTP_Click(object sender, EventArgs e)
    {
        lblOTP.Text = GenerateOTP(Convert.ToInt32(txtOTP.Text.Trim()));
    }

    public string GenerateOTP(int Length)
    {
        string _allowedChars = "#@$&*abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
        Random randNum = new Random();
        char[] chars = new char[Length];

        for (int i = 0; i < Length; i++)
        {
            chars[i] = _allowedChars[Convert.ToInt32((_allowedChars.Length - 1) * randNum.NextDouble())];
        }
        return new string(chars);
    }

Asp.Net VB Code to generate One Time Password(OTP)

Protected Sub btnGenerateOTP_Click(sender As Object, e As EventArgsHandles btnGenerateOTP.Click
        lblOTP.Text = GenerateOTP(Convert.ToInt32(txtOTP.Text.Trim()))
    End Sub

    Public Function GenerateOTP(Length As IntegerAs String
        Dim _allowedChars As String = "#@$&*abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
        Dim randNum 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) * randNum.NextDouble()))
        Next
        Return New String(chars)
    End Function

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.