TOTP 2FA Password
2 Factor Authentication Time-Based One-Time Password
TOTP算法
Python实现 适当简化 提供密钥即可生成一次性密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import base64 import hmac import struct import time
def ttotp(key): key = base64.b32decode(key.upper() + '=' * ((8 - len(key)) % 8)) counter = struct.pack('>Q', int(time.time() / 30)) mac = hmac.new(key, counter, 'sha1').digest() offset = mac[-1] & 0x0f binary = struct.unpack('>L', mac[offset:offset+4])[0] & 0x7fffffff return str(binary)[-6:].zfill(6)
if __name__ == '__main__': key = 'PRCFQ3SPFMOTIR2D' print(ttotp(key))
|