如何在python中结合使用base32和hotp(一次性密码)?

2024-05-19 03:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

对于大学练习,我想用python开发一个简单的hotp服务器客户机系统。在这种情况下,客户机向服务器发送一个密码和一个一次性密码。服务器知道这个秘密,计算当前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


Tags: import密码secretreturndefcounterarrayhmac
2条回答

发现错误: 机密必须是base32解码值,而不是将机密转换为base32。另外,必须对其进行解码,而不是对该值进行编码(“base64.b32decode(bytes(saved_secret,'utf-8'))”)

所以正确的主视图如下:

def main():
    secret = "V6X27L5P" #Base32 value
    secret = base64.b32decode(bytes(secret, 'utf-8'))
    one_time_password = hotp(secret, counter)

首先,必须指出secret.encode('UTF-8')的结果与base64.b32encode(bSecret)的结果具有完全相同的类型(对于这一点,base64.b64encode(bSecret))它们都返回{}对象。同样值得注意的是,Python中的implementation of ^{}没有提到base64/base32编码。所以简单的回答是,807244的预期结果只有在共享机密是base64/UTF-8编码的blob时才有效。在

这个简短的代码片段显示,您确实可以给hotp任何字节,并且它将得到一些结果(因为在示例中,hotp被多次调用,counter被更改)

# ... everything from your example above ...
secret = "1234"
secret_bytes = secret.encode("UTF-8")
secret_bytes
>>> b'1234'
b32_secret = base64.b32encode(bSecret)
b32_secret
>>> b'GEZDGNA='
b64_secret = base64.b64encode(bSecret)
b64_secret
>>> b'MTIzNA=='
hotp(secret_bytes, counter)  # just a UTF-8 blob works
>>> '110366'
hotp(b32_secret, counter)  # base32/UTF-8 also works
>>> '896513'
hotp(b64_secret, counter)  # base64/UTF-8 works as well
>>> '806744'

如果您更详细地了解为什么您希望807244为base32/UTF8 blob,我很乐意修改这个答案。在

相关问题 更多 >

    热门问题