通过python进行谷歌hotp身份验证

具体原理如下图(copy自网络):

代码如下图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import hmac
import hashlib
import base64
import struct
import time
import six
def get_hotp(secret_key, intervals_no, as_string=True, casefold=True, digest_method=hashlib.sha1, token_length=6):
if isinstance(secret_key, six.string_types):
secret_key = secret_key.encode('utf-8')
secret_key = secret_key.replace(b' ', b'')
try:
key = base64.b32decode(secret_key, casefold=casefold)
except TypeError:
raise TypeError('Incorrect secret_key: %s' % secret_key)
msg = struct.pack('>Q', intervals_no)
hmac_digest = hmac.new(key, msg, digest_method).digest()
ob = hmac_digest[19] if six.PY3 else ord(hmac_digest[19])
o = ob & 15
token_base = struct.unpack('>I', hmac_digest[o:o + 4])[0] & 0x7fffffff
token = token_base % (10 ** token_length)
if as_string:
return '{{:0{}d}}'.format(token_length).format(token)
else:
return token
if __name__ == '__main__':
while True:
secret = "liecol_Gao" # 去除=后转为b64后长度不能低于16
secret = base64.b32encode(s=secret.encode('utf-8'))
# print(secret)
hotp = get_hotp(secret_key=secret, intervals_no=int(time.time()) // 30, )
print(hotp)
time.sleep(30)

最后结果为:

注: 转载请注明出处,本文作者为 Liecol Gao, 本文标题为 通过python进行谷歌hotp身份验证