def compute_totp(secret, offset=0):
"""
Computes the current TOTP code.
:param secret: Base32 encoded secret.
:type secret: unicode
:param offset: Time offset (in steps, use eg -1, 0, +1 for compliance with RFC6238)
for which to compute TOTP.
:type offset: int
:returns: TOTP for current time (+/- offset).
:rtype: unicode
"""
assert(type(secret) == six.text_type)
assert(type(offset) in six.integer_types)
try:
key = base64.b32decode(secret)
except TypeError:
raise Exception('invalid secret')
interval = offset + int(time.time()) // 30
msg = struct.pack('>Q', interval)
digest = hmac.new(key, msg, hashlib.sha1).digest()
o = 15 & (digest[19] if six.PY3 else ord(digest[19]))
token = (struct.unpack('>I', digest[o:o + 4])[0] & 0x7fffffff) % 1000000
return u'{0:06d}'.format(token)
评论列表
文章目录