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.
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 EventArgs)
Handles
btnGenerateOTP.Click
lblOTP.Text = GenerateOTP(Convert.ToInt32(txtOTP.Text.Trim()))
End Sub
Public Function GenerateOTP(Length As Integer)
As 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
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
1 comments:
Click here for commentsIt is Most iportant containt of verification.....
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..