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

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);
}



1 comment:

  1. OTP SMS delivers instantly for Mobile Number Verification through HTTP API, XML API and Json API with 2 factor authentication.

    ReplyDelete

Powered by Blogger.