-
-
Save alexxroche/0353516724df5a453dd3c73f7206a786 to your computer and use it in GitHub Desktop.
TOTP module for Python.
This file contains hidden or 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
#!/usr/bin/env python2 | |
""" Implementation of RFC 4226: HMAC-Based One-Time Password Algorithm (HTOP), | |
and RFC 6238: Time-Based One-Time Password Algorithm (TOTP). | |
""" | |
__author__ = 'acoster' | |
__copyright__ = 'Copyright 2012, Alexandre Coster' | |
__fixed__ = 'ver 20181001003525 alexx' | |
import hmac, time, base64, struct, hashlib, sys | |
def get_hotp(secret, counter): | |
while len(secret) % 4 != 0: | |
secret = secret[:-1] | |
while len(secret) % 8 != 0: | |
secret += '=' | |
secret = base64.b32decode(secret, casefold=True) | |
counter = struct.pack('>Q', counter) | |
hash = hmac.new(secret, counter, hashlib.sha1).digest() | |
offset = ord(hash[19]) & 0xF | |
return (struct.unpack(">I", hash[offset:offset + 4])[0] & 0x7FFFFFFF) % 1000000 | |
def get_totp(secret): | |
return get_hotp(secret, int(time.time()) // 30) | |
if len(sys.argv) == 2: | |
print("{}".format(str(get_totp(sys.argv[1])).rjust(6, '0'))) | |
else: | |
print("Usage: totp.py <secret>") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment