#!/usr/bin/env python3
# https://github.com/susam/mintotp (20211227 - modified)

import base64
import hmac
import struct
import sys
import time
keyfile = ".totpkey"
digest='sha512'
digits = 6
drift = 0
time_step = 30
with open(keyfile) as f:
	key = f.readline().rstrip()
	key = "".join(key.split())

def hotp(key, counter, digits, digest):
	key = base64.b32decode(key.upper() + '=' * ((8 - len(key)) % 8))
	counter = struct.pack('>Q', counter)
	mac = hmac.new(key, counter, digest).digest()
	offset = mac[-1] & 0x0f
	binary = struct.unpack('>L', mac[offset:offset+4])[0] & 0x7fffffff
	return str(binary)[-digits:].zfill(digits)

def totp(key, time_step, digits, digest):
	return hotp(key, int((time.time()-drift) / time_step), digits, digest)

def main():
		print(totp(key,time_step,digits,digest))

if __name__ == '__main__':
	main()
