How to Generate One Time Password(OTP) in C#

How to Generate One Time Password(OTP) using C#. In this article, we will learn How to Generate One Time Password(OTP) in C#.

What is OTP?

OTP stands for a one-time password. It is a password that is valid for only one login session or transaction. It can be numeric as well as alphanumerical.OTPs or One Time Passwords are widely used by banks and other firms to validate the Mobile Numbers of their users. OTP’s generally have lengths between 5-10 characters.

The simplest example of an OTP is when you try to connect to a public Wi-Fi network, your mobile device receives an SMS containing a unique password and once you register with the correct password, the device gets connected to the network. We can easily do otp generation and verification in c#.

C# Code to Generate numeric OTP

When the Button is clicked, the length and the type values of the Password are fetched from the DropDownList and RadioButtonList. There are three strings,

  • First containing Upper Case Alphabets.
  • Second, containing Lower Case Alphabets.
  • Third one containing the 10 digits.

Then a loop is executed and inside the loop, a random number is used to fetch the character from the combination of Alphabets and Numeric strings or only the Numeric string based on the type selected in the RadioButtonList.

Inside the For Loop, a While loop is used to avoid repetition of the characters.

The generated unique random OTP i.e. One Time Password is displayed in the Label control.

Generate alphanumeric OTP in C#

Write the below-given code on the button click event to generate the alphanumeric OTP.

protected void GenerateOTP(object sender, EventArgs e)
{
    string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
    string numbers = "1234567890";
 
    string characters = numbers;
    if (rbType.SelectedItem.Value == "1")
    {
        characters += alphabets + small_alphabets + numbers;
    }
    int length = int.Parse(ddlLength.SelectedItem.Value);
    string otp = string.Empty;
    for (int i = 0; i < length; i++)
    {
        string character = string.Empty;
        do
        {
            int index = new Random().Next(0, characters.Length);
            character = characters.ToCharArray()[index].ToString();
        } while (otp.IndexOf(character) != -1);
        otp += character;
    }
    lblOTP.Text = otp;
}

Output

In this way, we learn How to Generate One Time Password(OTP) in C#.