Skip to content

Instantly share code, notes, and snippets.

@BastienClement
Created April 18, 2012 09:04
Show Gist options
  • Save BastienClement/2412198 to your computer and use it in GitHub Desktop.
Save BastienClement/2412198 to your computer and use it in GitHub Desktop.
Authenticator token generation
/// <summary>
/// 10^0..10^8 (NumDigits used in the HOTP)
/// </summary>
private static readonly int[] DigitsPower = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
private static int DynamicTruncate(byte[] hash)
{
int offset = hash[hash.Length - 1] & 15;
return ((hash[offset] & 127) << 24) + ((hash[offset + 1] & 255) << 16) + ((hash[offset + 2] & 255) << 8) +
(hash[offset + 3] & 255);
}
public string GenerateCode()
{
long time = (BlizzTime/30000);
byte[] timeBytes = BitConverter.GetBytes(time);
// Invert the endian-ness, giving us a big endian number
Array.Reverse(timeBytes);
var sha1 = new HMACSHA1(Token); // Secret Token
byte[] h = sha1.ComputeHash(timeBytes);
int code = DynamicTruncate(h)%DigitsPower[8];
return code.ToString().PadLeft(8, '0');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment