https://stackoverflow.com/questions/8529265/google-authenticator-implementation-in-python/
-
#!/usr/bin/env python
-
# coding= utf-8
-
'''
-
Created on 2017年9月29日
-
-
@author: babaoqi
-
'''
-
import string, random
-
import hmac, base64, struct, hashlib, time
-
-
-
def random_str(size=10):
-
#all_char = string.letters + string.digits + string.punctuation
-
all_char = string.letters + string.digits
-
rchars = [random.choice(all_char) for i in range(size)]
-
rstr = "".join(rchars)
-
return rstr
-
-
def get_secret():
-
rstr = random_str()
-
# random_str 长度必须是5的倍数, encode后最后才不含'='号
-
# 长度=10,encode返回长度为16
-
secret = base64.b32encode(rstr)
-
return secret.upper()
-
-
# 基于次数
-
def get_hotp_token(secret, intervals_no):
-
key = base64.b32decode(secret, True)
-
msg = struct.pack(">Q", intervals_no)
-
googleCode = hmac.new(key, msg, hashlib.sha1).digest()
-
o = ord(googleCode[19]) & 15
-
googleCode = (struct.unpack(">I", googleCode[o:o + 4])[0] & 0x7fffffff) % 1000000
-
# 如果验证码的第一位是0,则不会显示。此处判断若是5位码,则在第一位补上0
-
# 前面补0
-
sl = len(str(googleCode))
-
if sl < 6:
-
googleCode = "%s%s" % ('0' * (6 - sl), googleCode)
-
return googleCode
-
-
# 基于时间
-
def get_totp_token(secret):
-
period_seconds = 30
-
intervals_no = int(time.time()) // period_seconds
-
return get_hotp_token(secret, intervals_no)
-
-
if __name__ == '__main__':
-
secret = get_secret()
-
-
for i in xrange(0,30):
-
print secret, get_totp_token(secret), get_hotp_token(secret, i)
-
time.sleep(4)
-
-
exit(0)
-
# random_str 长度必须是5的倍数, encode后最后才不含'='号
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26250550/viewspace-2145604/
,如需转载,请注明出处,否则将追究法律责任。