pythonencryptioncryptography

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


So I tried to read the file and encrypt its content with cryptography.fernet but sometimes the file contains characters that can't be encrypted by whatever algorithm is being used in this library. I also tried a library called pyAesCrypt which has this function: pyAesCrypt.encryptFile("data.txt", "data.txt.aes", password). But it also can't encrypt some file types like gifs. I don't know much about the encryption algorithm happening in the background, but is there any way I can encrypt all files no matter what characters they contain? Or maybe encode them first to get rid of these characters then encrypt them? I'm just giving ideas based on the small knowledge I have about this topic.

The code I tried with Fernet library:

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)

When I try this with GIFs I get:

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

Solution

  • you must open file in binary mode for reading and writing. since encrypt method expect bytes as a parameter, this way you can encrypt any file no matter it's type.

    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)