Python-Python3 生成 Google Authenticator 的 6 位验证码
代码如下:
# -*- coding: utf-8 -*- import hmac import math import base64 import struct import hashlib import time def cal_google_code(secret_key): # secret key 的长度必须是 8 的倍数。所以如果 secret key 不符合要求,需要在后面补上相应个数的 "=" secret_key_len = len(secret_key) secret_key_pad_len = math.ceil(secret_key_len / 8) * 8 - secret_key_len secret_key = secret_key + "=" * secret_key_pad_len duration_input = int(time.time()) // 30 key = base64.b32decode(secret_key) msg = struct.pack(">Q", duration_input) google_code = hmac.new(key, msg, hashlib.sha1).digest() o = google_code[19] & 15 google_code = str((struct.unpack(">I", google_code[o:o+4])[0] & 0x7fffffff) % 1000000) # 生成的验证码未必是 6 位,注意要在前面补 0 if len(google_code) == 5: # Only if length of the code is 5, a zero will be added at the beginning of the code. google_code = '0' + google_code return google_code print(cal_google_code('your secret key'))
【完】