2021-08-20 12:44:03 +01:00
|
|
|
import base64
|
|
|
|
import hmac
|
2022-07-16 14:23:03 +02:00
|
|
|
import struct
|
2021-08-20 12:44:03 +01:00
|
|
|
import time
|
|
|
|
|
|
|
|
|
|
|
|
def hotp(key, counter, digits=6, digest="sha1"):
|
|
|
|
key = base64.b32decode(key.upper() + "=" * ((8 - len(key)) % 8))
|
|
|
|
counter = struct.pack(">Q", counter)
|
|
|
|
mac = hmac.new(key, counter, digest).digest()
|
2022-06-01 14:53:05 +02:00
|
|
|
offset = mac[-1] & 0x0F
|
|
|
|
binary = struct.unpack(">L", mac[offset : offset + 4])[0] & 0x7FFFFFFF
|
2021-08-20 12:44:03 +01:00
|
|
|
return str(binary)[-digits:].zfill(digits)
|
|
|
|
|
|
|
|
|
|
|
|
def totp(key, time_step=30, digits=6, digest="sha1"):
|
|
|
|
return hotp(key, int(time.time() / time_step), digits, digest)
|