Sunday, 29 November 2015

Generate unique OTP in asp.net using C#

In this article I am going to explain how to generate unique OTP (one time password) in asp.net

Description:

OTP stand for one time password. It is a password that is valid for only one login session or transaction. It is widely used by the banks for transactions. It can be numeric as well as alphanumerical.


HTML markup:
   <fieldset style="width:420px">
    <legend><strong>OTP Example</strong></legend>
     <table>
    <tr><td>Click to Generate OTP :</td><td>
        <asp:Button ID="btnOTP" runat="server" Text="Generate OTP"/></td></tr>
     <tr><td></td><td></td></tr>
      <tr id="idotp" runat="server" visible="false"><td><strong>OTP</strong> :</td><td>
          <asp:Label ID="lblotp" runat="server"></asp:Label></td></tr>
    </table>

    </fieldset>


Generate numeric OTP
On button click write the below given to generate OTP:
C# code:


protected void btnOTP_Click(object sender, EventArgs e)
    {
        GenerateOTP();
    }

    private void GenerateOTP()
    {
        try
        {
            int length = 6;
            string numbers = "0123456789";
            Random objrandom = new Random();
            string strrandom = string.Empty;
            int noofnumbers = length;
            for (int i = 0; i < noofnumbers; i++)
            {
                int temp = objrandom.Next(0, numbers.Length);
                strrandom += temp;
            }
            lblotp.Text = strrandom;
            idotp.Visible = true;
        }
        catch (Exception ex)
        {
        }
    }

No comments:

Post a Comment