Reference : Kyle Spearrin (kspearrin)
An implementation of TOTP and HOTP which are commonly used for multi factor authentication by using a shared key between the client and the server to generate and verify one time use codes.
Code
long _counter = 0;
string isRepeat = "N";
string currentOTP = string.Empty;
bool isValidOTP = false;
//Generate secret key random
var key = KeyGeneration.GenerateRandomKey(20);
var base32String = Base32Encoding.ToString(key);
var base32Bytes = Base32Encoding.ToBytes(base32String);
Console.WriteLine($ "Random Secret Key : { base32String}\r\n");
do {
Console.WriteLine("HOTP Generation Test");
Console.WriteLine("====================\r\n");
byte[] secretKey = new UTF8Encoding().GetBytes("sagun"); //generate key manually
Hotp _HOTP = new Hotp(base32Bytes, mode: OtpHashMode.Sha512);
long currentCounter = ++_counter;
var hOTPCode = _HOTP.ComputeHOTP(currentCounter);
Console.WriteLine($ "Your OTP : {hOTPCode} ");
Console.Write("Enter your OTP : ");
currentOTP = Console.ReadLine();
isValidOTP = _HOTP.VerifyHotp(currentOTP, currentCounter);
if (isValidOTP) Console.WriteLine("Your OTP is valid");
else Console.WriteLine("Your OTP is invalid!!!");
Console.Write("Generate again ? Y/y/N/n : ");
isRepeat = Console.ReadLine();
Console.WriteLine();
} while ( isRepeat . Equals ("Y") || isRepeat.Equals("y"));
Console.WriteLine("=== Thank You ===");