Skip to content

Instantly share code, notes, and snippets.

@consoledotblog
Last active August 29, 2015 13:57
Show Gist options
  • Save consoledotblog/9485772 to your computer and use it in GitHub Desktop.
Save consoledotblog/9485772 to your computer and use it in GitHub Desktop.
Two Factor Authentication for the masses
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
long counter = GetCurrentTCounter();
private long GetCurrentTCounter()
{
long seconds = (long)DateTime.UtcNow.Subtract(baseTime).TotalSeconds;
return seconds / interval;
}
private byte[] GetHMAC(long counter, byte[] Key)
{
byte[] counterBytes = BitConverter.GetBytes(counter);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
}
using (HMACSHA1 mac = new HMACSHA1(Key))
{
return mac.ComputeHash(counterBytes);
}
}
int mod = (int)Math.Pow(10, 6);
private int GetOTPValue(byte[] hash, int mod)
{
int offset = hash.Last() & 0x0f;
int binCode = (hash[offset] & 0x7f) << 24 |
(hash[offset + 1] & 0xff) << 16 |
(hash[offset + 2] & 0xff) << 8 |
(hash[offset + 3] & 0xff);
int otp = binCode % mod;
return otp;
}
otp.ToString().PadLeft(6, '0');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment