Without Database:-
Generate OPT :-Random random = new Random();
byte[] time = BitConverter.GetBytes(DateTime.Now.ToBinary());
byte[] key = BitConverter.GetBytes(random.Next());
string token = Convert.ToBase64String(time.Concat(key).ToArray());
For Checking OTP Expired or NOT:-
byte[] data = Convert.FromBase64String(OTP Entered by User);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.Now.AddSeconds(-50)) ///Here you can define the OTP interval
lblDecOTP.Text = "OTP is expired....";
else
lblDecOTP.Text = "OTP is active....";
With Database:-
Insert OTP IN Database:-
public void InsertOTPinDB() {
Random rnd = new Random();randomNumber = (rnd.Next(100000, 999999)).ToString();
string query = "INSERT INTO OTPhistroytbl (id,Customer_No,User_Id,OTP,ctime_Stamp,status) VALUES (@id,@Customer_No,@User_Id,@OTP,@ctime_Stamp,@status) "; cmd = new SqlCommand(query, con); con.Open(); cmd.Parameters.AddWithValue("@id", 2); cmd.Parameters.AddWithValue("@Customer_No", Cust_No.ToString()); cmd.Parameters.AddWithValue("@User_Id", Uname); cmd.Parameters.AddWithValue("@OTP", randomNumber); cmd.Parameters.AddWithValue("@ctime_Stamp", System.DateTime.Now.ToString()); cmd.Parameters.AddWithValue("@status", "1"); cmd.ExecuteNonQuery(); con.Close(); }
Verfiry OTP:-
{
lblMsg.Visible = true;
adp = new SqlDataAdapter("SELECT ctime_Stamp FROM OTPhistroytbl WHERE OTP='" + txtOTP.Text + "'", con);
adp.Fill(dt);
DateTime OtpCrtDate = Convert.ToDateTime(dt.Rows[0][0].ToString());
if (txtOTP.Text != randomNumber)
{
TimeSpan timeSub = DateTime.Now - OtpCrtDate;
if (timeSub.TotalMinutes < 300)
{
cmd = new SqlCommand("update OTPhistroytbl set status='0' where OTP='" + txtOTP.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "logined successfully";
con.Close();
}
else
lblMsg.Text = "Sorry but your OTP is very old. Get a new one";
}
else
lblMsg.Text = "Sorry, Your OTP is Invalid. Try again, please.";
}
No comments:
Post a Comment