python - 我不知道如何修复 TypeError : can't concat str to bytes mean

标签 python byte

我编写了一个函数来加密给定的文本文件。下面的代码是该函数的一小部分。

            #pad it before encrypting it
            elif len(chunk) % 16 != 0:
                chunk += ' ' * (16 - len(chunk) % 16)
            #write encrypted data into output file
            out_file.write(encryptor.encrypt(chunk))

每当我尝试使用该函数时,我都会收到一个错误,该错误指向最后一行: “TyprError:无法将 str 连接到字节”。我不确定我需要做什么才能修复此错误。我尝试了一些事情,但它们最终导致我陷入更多类似的错误。任何指导将不胜感激。 加密器如下。

encryptor  = PKCS1_OAEP.new(pub_key)

最佳答案

您的加密方法 encryptor.encrypt() 很可能接受 bytes 作为参数,而不是 str。它也很可能返回字节。所以我建议您使用如下的encode/decode方法(utf-8编码示例):

 out_file.write(encryptor.encrypt(chunk.encode('utf-8')).decode('utf-8'))

关于python - 我不知道如何修复 TypeError : can't concat str to bytes mean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49013719/

相关文章:

python - 使用 pyspark 将 csv 文件转换为 parquet 文件 : Py4JJavaError: An error occurred while calling o347. parquet 错误

python - 如何在 Python 中查找字符串中的空字节?

python - 为什么 PyQt5 小部件有时具有相同的 id?

python - 对 Pandas 数据框应用/矢量化/加速按列清理功能

JAVA 以 block 的形式读取文件,每个 block 为十六进制

c++ - 将 BYTE 缓冲区的特定部分复制到结构+

c - 在 linux 上使用 od 命令有倒退吗?

C++ 如何加密字节数组?

python - 无法打开 Flask 应用程序的 url

python - 在 Mac OSX 10.6.8 上安全地从 usr/local/bin 中删除程序?