对于大学练习,我想用 python 开发一个简单的 hotp 服务器-客户端系统。在这种情况下,客户端向服务器发送密码和一次性密码。服务器知道秘密,计算当前的热点并比较它收到的值。到目前为止,一切都很好。使用纯文本,这可以很好地工作,并且计算的值与我使用 iOS 应用程序“OTP Auth”时得到的值相同。但也有可能结合 base32 计算 OTP。所以我添加了几行将明文编码为base32,但现在输出不正确。
假设我们使用秘密“1234”,所以明文输出将是“110366”。那行得通。但是,如果我将秘密编码为 base32,则输出应该是“807244”,但我的程序计算的是“896513”。有人知道为什么会这样吗?
我已经尝试使用不同的秘密并在不同的应用程序上进行了检查。总是一样的结果。
import hmac
import hashlib
import array
import base64
counter = 0
digits = 6 #Anzahl der Zeichen
def hotp(secret, c):
global digits
counter = extendCounter(c)
hmac_sha1 = hmac.new(secret, counter, hashlib.sha1).hexdigest()
return truncate(hmac_sha1)[-digits:]
def truncate(hmac_sha1):
offset = int(hmac_sha1[-1], 16)
binary = int(hmac_sha1[(offset * 2):((offset * 2) + 8)], 16) & 0x7fffffff
return str(binary)
def extendCounter(long_num):
byte_array = array.array('B')
for i in reversed(range(0, 8)):
byte_array.insert(0, long_num & 0xff)
long_num >>= 8
return byte_array
def main():
secret = "1234"
bSecret = secret.encode("UTF-8")
bSecret = base64.b32encode(bSecret)
otp = hotp(bSecret, counter)
one_time_password = otp
我希望 807244 作为输出,但输出是 896513