Google OAuth在Python 3中

2024-04-27 03:53:25 发布

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

我跟随this awesome answer在Python中实现googleoauth。但是,当我尝试在Python 3中运行时,出现以下错误:

TypeError: ord() expected string of length 1, but int found

此错误由此行引发:

o = ord(h[19]) & 15

尝试o = ord(str(h[19])) & 15导致:

TypeError: ord() expected a character, but string of length 3 found

这在Python3中发生,但在Python2中没有,这使我认为有些类型在版本之间发生了变化。这是相关代码:

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

我试着跟随this question的答案,但他们没有帮助。第一个答案没有帮助,因为我没有为keymsg使用字符串文字。这是我试图实现第二个答案的建议:

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    key_bytes = bytes(key, 'latin-1')

    msg = struct.pack(">Q", intervals_no)
    msg_bytes = bytes(msg, 'latin-1')

    h = hmac.new(key_bytes, msg_bytes, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

此代码在key_bytes = <...>msg_bytes = <...>上引发了此错误:

TypeError: encoding without a string argument

utf-8代替latin-1也有同样的结果。你知道吗

如果我print(key, msg),我会得到这样的结果,这表明它们已经是类似字节的形式了:

b'fooooooo37' b'\x00\x00\x00\x00\x02\xfa\x93\x1e'

打印的msg解释了上面的... string of length 3 found错误。你知道吗


我不知道从这里到哪里去。任何建议/解决方案太好了!你知道吗


Tags: ofkeynosecretstringbytes错误msg
1条回答
网友
1楼 · 发布于 2024-04-27 03:53:25

hmac.new()返回字节字符串。在python3中,这是一个整数数组。因此h[19]是一个整数。只需使用该int而不是调用ord()。或者把h解码成str

相关问题 更多 >