pythonencryptionpicklefernet

Unpickling and decrypting a file in memory in Python 3.7


I have a pickled .pkl file that I encrypted using the following encrpytion:

def encrypt_file(filepath, key):
    f = Fernet(key)
    with open(filepath, "rb") as file:
        file_data = file.read()

    encrypted_data = f.encrypt(file_data)
    with open(filepath, "wb") as file:
        file.write(encrypted_data)

I now want to decrypt and unpickle the file in memory. This is because I don't want to alter the actual file in the storage.

I tried the following:

f = Fernet(key)
with open(filepath, "rb") as file:
    encrypted_data = file.read(file)
    decrypted_data = f.decrypt(encrypted_data)
    vectorizer = p.load(decrypted_data)

The original file is written as a pickled .pkl and then encrypted.

So I figured I could just load the file in Python, decrypt it and then unpickle it. Unfortunately I get the following error and I'm not sure how to fix it:

web_1 | vectorizer = p.load(decrypted_data)
web_1 | TypeError: file must have 'read' and 'readline' attributes

Solution

  • Use pickle.loads():

    f = Fernet(key)
    with open(filepath, "rb") as file:
        encrypted_data = file.read(file)
        decrypted_data = f.decrypt(encrypted_data)
        vectorizer = p.loads(decrypted_data)