出于安全性的考虑 现在有很多网站要求启用2FA(两步认证),例如Github,某个不能透露的网站等等。常见的方式是启用两步验证时网站提供一个验证码,说让你用支持TOTP的App如Google Authenticator等扫描二维码,然后生成一个Code填入进行验证。启用TOTP的两步验证后进行敏感性操作如修改邮箱,修改密码等时会额外要求输入效验码,此限制可有效避免密码泄露时造成更大的损失。
以下是一段基于Python原生库生成TOTP效验码的脚本
[Python] 纯文本查看 复制代码 import hmac, base64, struct, hashlib, time
def get_hotp_token(secret, intervals_no):
key = base64.b32decode(secret, True)
# decoding our key
msg = struct.pack(">Q", intervals_no)
# conversions between Python values and C structs represente
h = hmac.new(key, msg, hashlib.sha1).digest()
o = h[19] & 15
# Generate a hash using both of these. Hashing algorithm is HMAC
h = (struct.unpack(">I", h[o:o + 4])[0] & 0x7fffffff) % 1000000
# unpacking
return h
def get_totp_token(secret):
# ensuring to give the same otp for 30 seconds
x = str(get_hotp_token(secret, intervals_no=int(time.time()) // 30))
# adding 0 in the beginning till OTP has 6 digits
while len(x) != 6:
x += '0'
return x
def exec():
print(get_totp_token('VRRWFDP6VWJOKBBB'))
pass |