如何将字符转换为 Python 3 Base64 编码的类似字节的对象?

问题描述 投票:0回答:1

我在 Python 2 中有一个函数,可以将字符串加密为 Base64 编码的对象。 当我在 Python 3 中运行相同的内容时,我得到不同的输出。连同以下类型错误:

TypeError:需要类似字节的对象,而不是“str”

如何获得正确的类似字节的对象,以便将字符串“hello world”编码为 Base64?

    enc = []
    clear = "hello world"
    key = "1234567890"
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    print ("enc:", enc)
    print (base64.urlsafe_b64encode("".join(enc)))

在 Python 2 中运行它,给出以下输出:

enc: ['\x99', '\x97', '\x9f', '\xa0', '\xa4', 'V', '\xae', '\xa7', '\xab', '\ x9c', '\x95']

Base64 编码:mZefoKRWrqernJU=

在 Python 3 中运行此程序,会为加密列表

enc
和 TypeError:

提供不同的输出

enc: ['\x99', '\x97', '\x9f', '\xa0', '¤', 'V', '®', '§', '«', '\x9c', ' \x95']

如何获得与 Python3 中运行相同的结果?

python-3.x python-2.7 encryption base64
1个回答
0
投票

根据topaco提供的解释和示例代码,这是工作编码函数:

def encode(key, clear):
    enc = []
    bkey = key.encode()
    bclear = clear.encode()
    for i in range(len(bclear)):
        key_c = bkey[i % len(bkey)]
        enc_c = (bclear[i] + key_c) % 256
        enc.append(enc_c)
    encB64 = base64.urlsafe_b64encode(bytes(enc))  # convert list to bytes-like object
    print("base64 encoded:", encB64.decode())
    return encB64.decode()
© www.soinside.com 2019 - 2024. All rights reserved.