Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Genarate One Time Password String
WhatsApp
Vishal Jadhav
Sep 14
2014
4.5
k
0
4
public
static
string
TOTPGenerator(
string
uniqueIdentity)
{
string
oneTimePassword =
""
;
DateTime dateTime = DateTime.Now;
string
_strParsedReqNo = dateTime.Day.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Month.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Year.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Hour.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Minute.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Second.ToString();
_strParsedReqNo = _strParsedReqNo + dateTime.Millisecond.ToString();
_strParsedReqNo = _strParsedReqNo + uniqueCustomerIdentity;
//Append above string with Policy number to get desired output.
Console.WriteLine(
"TOTP value: "
+ _strParsedReqNo);
using
(MD5 md5 = MD5.Create())
{
//Get hash code of entered request id in byte format.
byte
[] _reqByte = md5.ComputeHash(Encoding.UTF8.GetBytes(_strParsedReqNo));
//convert byte array to integer.
int
_parsedReqNo = BitConverter.ToInt32(_reqByte, 0);
string
_strParsedReqId = Math.Abs(_parsedReqNo).ToString();
//Check if length of hash code is less than 9.
//If so, then prepend multiple zeros upto the length becomes atleast 9 characters.
if
(_strParsedReqId.Length < 9)
{
StringBuilder sb =
new
StringBuilder(_strParsedReqId);
for
(
int
k = 0; k < (9 - _strParsedReqId.Length); k++)
{
sb.Insert(0,
'0'
);
}
_strParsedReqId = sb.ToString();
}
oneTimePassword = _strParsedReqId;
}
//Adding random letters to the OTP.
StringBuilder builder =
new
StringBuilder();
Random random =
new
Random();
string
randomString =
""
;
for
(
int
i = 0; i < 4; i++)
{
randomString += Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
}
//Deciding number of characters in OTP.
Random ran =
new
Random();
int
randomNumber = ran.Next(2, 5);
Random num =
new
Random();
//Form alphanumeric OTP and rearrange it reandomly.
string
otpString = randomString.Substring(0, randomNumber);
otpString += oneTimePassword.Substring(0, 7 - randomNumber);
oneTimePassword =
new
string
(otpString.ToCharArray().OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
return
oneTimePassword;
}
learn C#
Generate OTP string C#
code for OTP string