Skip to content

Instantly share code, notes, and snippets.

@stephen
Created July 9, 2014 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephen/a5e4a0130c2d12e4a17f to your computer and use it in GitHub Desktop.
Save stephen/a5e4a0130c2d12e4a17f to your computer and use it in GitHub Desktop.
import time;
import hmac;
import hashlib;
import os;
import math;
import base64;
import struct;
def get_hotp(secret, counter):
# get and decode shared secret
key_string = secret.upper();
key_material =base64.b32decode(key_string.encode());
hmac_gen = hmac.new(key_material, counter, hashlib.sha1);
hmac_res = hmac_gen.digest(); # generate hmac-sha1 hash
offset = hmac_res[19] & 0xf; # get offset
bin_int = struct.unpack(">I", hmac_res[offset:offset+4])[0]; #pull bytes from specific offset
bin_int = bin_int & 0x7fffffff;
return int(bin_int % (math.pow(10,6))); # get numerical values to present to user
def get_totp(secret):
counter = struct.pack(">Q", int(time.time() / 30)); # use time based counter, 30 second refresh intervals
return get_hotp(secret, counter);
print("");
print("google authenticator totp hash generator\n(c) stephen wan 2012\n");
secret = input("Enter secret key: ");
print("");
print("TOTP Hash - cycle # - position #");
l_hash = -1;
while (1):
totp_hash = get_totp(secret);
if l_hash != totp_hash and l_hash != -1:
print("");
l_hash = totp_hash;
print(totp_hash, "- cycle #", int(time.time() / 30), "- position #", str(int(time.time() % 30)).zfill(2), end="\r");
time.sleep(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment