Created
September 21, 2018 20:07
-
-
Save lachesis/c427213d71adcbf216ced93c47517ce2 to your computer and use it in GitHub Desktop.
Quick Py2/Py3 TOTP Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function, division, unicode_literals | |
import sys, time, re, struct, base64, hmac, hashlib | |
def get_hotp(secret, counter): | |
"""Return the HMAC-Based One-Time Password for the the given secret (base32 encoded) and the counter. | |
>>> [get_hotp('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', i) for i in xrange(10)] | |
[755224, 287082, 359152, 969429, 338314, 254676, 287922, 162583, 399871, 520489] | |
""" | |
secret = re.sub(r'\s*', '', secret) # remove whitespace | |
secret = secret.upper() # uppercase | |
if len(secret) % 8 != 0: | |
secret += '=' * (8 - len(secret) % 8) # base32 padding | |
secret = base64.b32decode(secret) | |
counter = struct.pack('>Q', counter) | |
hash = hmac.new(secret, counter, hashlib.sha1).digest() | |
offset = ord(hash[19:20]) & 0xF | |
val = (struct.unpack(">I", hash[offset:offset + 4])[0] & 0x7FFFFFFF) % 1000000 | |
return '{0:06d}'.format(val) | |
print(get_hotp(sys.argv[1], int(time.time()//30))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment