谷歌验证的密钥忘了
请问怎样才可以通过时间和对应的验证码算出16位的密钥?
下面是一个示例代码:
import hmac
import base64
import struct
import hashlib
# 输入之前记录的两个验证码和时间戳
code1 = '123456' # 第一个验证码
code2 = '654321' # 第二个验证码
timestamp = 1633486177 # 时间戳
# 计算时间戳的时间差
timestep = int(timestamp / 30)
# 计算密钥的初始值
secret = base64.b32decode('<your-secret-key>')
msg = struct.pack('>Q', timestep)
h = hmac.new(secret, msg, hashlib.sha1).digest()
o = h[19] & 15
h = (struct.unpack('>I', h[o:o + 4])[0] & 0x7fffffff) % 1000000
# 通过两个验证码计算密钥
for _ in range(0, 9999):
msg = struct.pack('>Q', timestep - _) # 逆推时间戳
h = hmac.new(secret, msg, hashlib.sha1).digest()
o = h[19] & 15
code = str((struct.unpack('>I', h[o:o + 4])[0] & 0x7fffffff) % 1000000).zfill(6)
if code == code1:
print('Initial key:', secret)
print('Time step:', timestep - _)
print('Code:', code)
break
在这个示例中,我们假设已经记录了两个验证码为 '123456' 和 '654321',以及时间戳为 1633486177。我们反推出时间戳的时间差为 54449539,通过这个时间差和初始密钥计算出初始验证码,然后在逆推时间戳并计算每个时间戳对应的验证码,直到找到与第一个验证码相等的验证码为止,这个时候对应的时间戳就是初始时间。