TypeError:需要一个类似字节的对象,而不是'int'

时间:2019-09-21 02:35:30

标签: python-3.x

嘿,我正在尝试cryptography的python模块。因此,我编写了一个“加密”(不是很新手的代码)文本并将其加密的代码,但是当我尝试保存加密的字节时,我得到一个“ TypeError:需要一个类似字节的对象,而不是'int '”。这很奇怪,因为我查看了“ encrypted_message”的类型及其一个类字节。

def encrypt(paswd, formated_data):
    #generates the salt
    digest = hashes.Hash(hashes.SHA256(), default_backend())
    digest.update(bytes(paswd, "utf-8"))
    salt = digest.finalize()

    kdf = PBKDF2HMAC(
        algorithm = hashes.SHA256,
        length = 32,
        salt = salt,
        iterations = 1000000,
        backend = default_backend()
    )
    key = kdf.derive(bytes(paswd, 'utf-8'))
    iv = os.urandom(16)
    encryptor = Cipher(algorithms.AES(key), modes.CTR(iv), default_backend()).encryptor()
    #untill this line of code everything works fine
    encrypted_msg = encryptor.update(bytes(formated_data, "utf-8")) + encryptor.finalize()

    print(type(encripted_msg)) #this prints <class 'bytes'>

    with open ("./vault/locked.aes", mode = "wb") as f:
        f.writelines( encripted_msg ) #and here i get the error

顺便说一句,我正在使用python 3.6.8

1 个答案:

答案 0 :(得分:0)

好的,我想出了解决办法。首先,python中的字节类将数据存储为列表,如果需要,您可以在循环中读取数据的每个字节。因此,二进制数据文件中的方法“ writelines()”不使用“ \ n”结束每一行,而是将每个字节写入bytes类变量中,只需要将其转换为列表即可,该方法将读取每个叮咬并将其写入文件。