Python 如何加密任何文件,无论它是什么类型?

How to encrypt any file no matter what type it is with Python?

所以我尝试读取文件并使用 cryptography.fernet 加密其内容,但有时文件包含无法通过该库中使用的任何算法加密的字符。我还尝试了一个名为 pyAesCrypt 的库,它具有以下功能:pyAesCrypt.encryptFile("data.txt", "data.txt.aes", password)。但它也不能加密某些文件类型,如 gif。 我不太了解后台发生的加密算法,但是有什么方法可以加密所有文件,无论它们包含什么字符?还是先对它们进行编码以摆脱这些字符,然后再对它们进行加密?我只是根据我对这个话题的小知识给出一些想法。

我用 Fernet 库尝试的代码:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)

with open(filename, "r") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data.encode()).decode()

with open(filename, "w") as file:
    file.write(encrypted_data)

当我用 GIF 尝试这个时,我得到:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 466: character maps to <undefined>

您必须以二进制模式打开文件以进行读写。由于 encrypt 方法需要字节作为参数,因此您可以加密任何文件,无论其类型如何。

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)

with open(filename, "rb") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data)

with open(filename, "wb") as file:
    file.write(encrypted_data)