Skip to content

Instantly share code, notes, and snippets.

@sadrakgunadi
Created January 25, 2019 14:51
Show Gist options
  • Save sadrakgunadi/6c5a132c6cbce09c82b3ad84d85b4b44 to your computer and use it in GitHub Desktop.
Save sadrakgunadi/6c5a132c6cbce09c82b3ad84d85b4b44 to your computer and use it in GitHub Desktop.
TOTP & HOTP .Net Framework

Otp.NET ( TOTP & HOTP)

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 ===");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment