I have a pickled .pkl
file that I encrypted using the following encrpytion:
JavaScript
x
9
1
def encrypt_file(filepath, key):
2
f = Fernet(key)
3
with open(filepath, "rb") as file:
4
file_data = file.read()
5
6
encrypted_data = f.encrypt(file_data)
7
with open(filepath, "wb") as file:
8
file.write(encrypted_data)
9
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:
JavaScript
1
6
1
f = Fernet(key)
2
with open(filepath, "rb") as file:
3
encrypted_data = file.read(file)
4
decrypted_data = f.decrypt(encrypted_data)
5
vectorizer = p.load(decrypted_data)
6
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:
JavaScript
1
3
1
web_1 | vectorizer = p.load(decrypted_data)
2
web_1 | TypeError: file must have 'read' and 'readline' attributes
3
Advertisement
Answer
Use pickle.loads()
:
JavaScript
1
6
1
f = Fernet(key)
2
with open(filepath, "rb") as file:
3
encrypted_data = file.read(file)
4
decrypted_data = f.decrypt(encrypted_data)
5
vectorizer = p.loads(decrypted_data)
6