user21001211
user21001211

Reputation: 1

File decryption in python with Fernet

When I try to decrypt text file it get me error 'bytes' object has no attribute 'decrypt'. Here's a code:

k = open('C:/Documents/key.key', 'rb')
key = k.read()
k.close()

f = open('C:/Documents/encrypted.txt', 'rb')
enc = f.read()
f.close()

decrypted = key.decrypt(enc)

I tried to change key and encrypted file class to string but it gives the same error 'str' object has no attribute 'decrypt'. Thanks for help :)

Upvotes: 0

Views: 407

Answers (1)

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

Currently you are working with the output of the file itself. You need to instantiate an object with the key to be able to do anything besides look at the bytes. The best way to think about this is that when you open the file and read it, you only get back the bytes of that file, which can't do anything unless interpreted by "something else." That "something else" is the class Fernet which has a method which allows you to decrypt another set of bytes.

from cryptography.fernet import Fernet

k = open('C:/Documents/key.key', 'rb')
key = Fernet(k.read())
k.close()

f = open('C:/Documents/encrypted.txt', 'rb')
enc = f.read()
f.close()

decrypted = key.decrypt(enc)

Upvotes: 1

Related Questions