AttributeError: '_io.TextIOWrapper' object has no attribute 'encrypt' - python

Im trying to add on to a project listed on https://www.thepythoncode.com/article/encrypt-decrypt-files-symmetric-python which is a text/file encryption setup with python, but every time I try to run the code, I hit the part of the code where it is actually encrypting the file and I'm getting the attribute error listed above
Full Error:
Traceback (most recent call last):
File "/Users/--------/Desktop/CODE/Python/TFEncrypter/TFEncrypter.py", line 38, in
<module>
encrypted_data = f.encrypt(file_data)
AttributeError: '_io.TextIOWrapper' object has no attribute 'encrypt'
Relevant Code:
""" IMPORTING AND DEFINITIONS """
import os
from cryptography.fernet import Fernet
def write_key():
key = Fernet.generate_key()
with open("key.tfe", "wb") as key_file:
key_file.write(key)
def load_key():
return open("key.tfe", "rb").read()
def make_file():
open("tte.txt", "x")
def encrypt(filename, key):
f = Fernet(key)
""" START OF PROGRAM """
path="key.tfe"
if os.path.isfile(path):
load_key()
task = input("Would You Like To Encrypt Or Decrypt A File?")
if type(task) == str:
if task == "Encrypt" or "encrypt":
task = input("Would You Like To Create A New File To Encrypt, Or Encrypt A Pre-Existing File (Note: Pre-Existing Files Must Be Named tte.txt) ANSWER AS: 'NEW FILE' or 'OLD FILE'")
if task == "NEW FILE":
path="tte.txt"
if os.path.isfile(path):
towrite = input("Text to encrypt in file:")
f = open("tte.txt", "w")
f.write(towrite)
with open("tte.txt", "rb") as file:
file_data = file.read()
encrypted_data = f.encrypt(file_data)
with open("encrypted.tfe", "wb") as file:
file.write(encrypted_data)
else:
make_file()
towrite = input("Text to encrypt in file:")
f = open("tte.txt", "w")
f.write(towrite)
with open("tte.txt", "rb") as file:
file_data = file.read()
encrypted_data = f.encrypt(file_data)
with open("encrypted.tfe", "wb") as file:
file.write(encrypted_data)

I have faced similar experience many times using Fernet. Try with simple library called
simplecrypt. You can install this library using pip install simple-crypt
Below is one example for the usage of the simplecrypt
import pandas as pd
from io import StringIO
from simplecrypt import encrypt, decrypt
#Create a dataframe
data = {'Date': ['2019-10-10', '2019-10-12', '2019-10-15'], \
'Credit Amount (SGD)': [40.00, 500.00, 60.00],\
'Transaction type': ['CC *1234', 'Bank transfer', 'CC *1234']}
df = pd.DataFrame(data)
#store in csv format
data_csv = df.to_csv(index=False)
#Encrypt the data by giving password
encdata = encrypt("provide password", data_csv)
#Store encrypted data in file
file_w = open('file.enc', 'wb')
file_w.write(encdata)
file_w.close()
#Decrypt the data from the file
file_r = open('file.enc','rb').read()
CSVplaintext = decrypt("provide the same password", file_r).decode('utf8')
DATA=StringIO(CSVplaintext)
df = pd.read_csv(DATA)
This is very simple to use for encryption and decryptionenter code here

Related

I am having an error with decryption with the cryptography module

I am writing a password manager, but am getting this error when run all of a sudden, ive tried googling, and couldnt find anything. the code runs, but then suddenly gives an error.
Traceback:
hello, thank you for using APM. enter 'help' for help. enjoy!
> find google
"google", "google.com", "AntispleneticMoonlighty", "#{6P=,U{;%^AMO+", "number- 1"
Traceback (most recent call last):
File "D:\CODING\Python\APM.py", line 80, in <module>
db.decrypt()
File "D:\CODING\Python\APM.py", line 44, in decrypt
decrypted = fernet.decrypt(original)
File "C:\Users\Anton\AppData\Local\Programs\Python\Python310\lib\site-packages\cryptography\fernet.py", line 85, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Users\Anton\AppData\Local\Programs\Python\Python310\lib\site-packages\cryptography\fernet.py", line 121, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
Press any key to continue . . .
the code is listed below (trimmed), the error is referring to line 44(shown below):
Code:
import PGL
from cryptography.fernet import Fernet
import os
import logging as lg
class APMDatabase:
def __init__(self, keyfile_path, database_path):
global start
self.keyfile_path = keyfile_path
self.database_path = database_path
print(start)
def read_key(self):
with open(self.keyfile_path, "rb") as keyfile:
return keyfile.read()
def encrypt(self):
key = self.read_key()
fernet = Fernet(key)
with open(self.database_path, "rb") as file:
original = file.read()
encrypted = fernet.encrypt(original)
with open(self.database_path, "wb") as encfile:
encfile.write(encrypted)
def decrypt(self):
key = self.read_key()
fernet = Fernet(key)
with open(self.database_path, "rb") as file:
original = file.read()
decrypted = fernet.decrypt(original) #THIS IS THE LINE WITH THE ERROR
with open(self.database_path, "wb") as decfile:
decfile.write(decrypted)
def find(self, name):
db.decrypt()
with open(self.database_path, "r") as database:
content = database.readlines()
for i in content:
if name in i:
print(i)
return i
db.encrypt()
db = APMDatabase(
keyfile_path="D:\\CODING\\Python\\APMKEY.APMKEY",
database_path="D:\\CODING\\Python\\APMDatabase.APMDATA",
)
while True:
db.decrypt()
number = len((open("D:\\CODING\\Python\\APMDatabase.APMDATA")).readlines())
db.encrypt()
query = input("> ")
elif "find" in query:
data = query.split(" ")[1]
if data == "(all)":
try:
db.find('"')
except:
lg.error("404")
try:
db.find(data)
except:
lg.error("404")

fernet: cryptography.fernet.InvalidToken when decrypting a file

I'm trying to decrypt a string using fernet. My code (assume files already exist with pre-filled data):
import hashlib
import bcrypt
from cryptography.fernet import Fernet
import base64
#encrypting
############################################################
file = open('message.txt', 'r+')
message = file.read()
file.close()
password = input("Enter password: ")
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
file = open('message.ivf', 'w+')
file.write(str(encMessage))
file.close()
############################################################
#decrypting
file = open('message.ivf', 'r+')
token = file.read()
file.close()
token = token.encode('utf-8')
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)
#token = fernet.encrypt(message)
d = fernet.decrypt(token)
print(d)
This returns the error
cryptography.fernet.InvalidToken
While decrypting. I'm unsure on what to do. I have viewed many questions but none have a fix for me. Links:
Stack Overflow question 1
Stack Overflow question 2
Stack Overflow question 3
Thanks in advance

Why does my cryptography python program not work?

I am trying to write a program to encrypt and decrypt messages. Here is the traceback:
Traceback (most recent call last):
File "C:\Users\notelling\OneDrive\Desktop\pyprojects\crypto.py", line 15, in
f = Fernet(key)
NameError: name 'key' is not defined
Here is my code:
from cryptography.fernet import Fernet
import os
if os.path.isfile("encryption.key"):
file = open("encryption.key", "rb")
filec = file.read().decode()
else:
key = Fernet.generate_key()
file = open('encryption.key', 'wb')
file.write(key.encode()) # The key is type bytes still
file.close()
print("Key generated.")
mode = input("Please enter mode (e/d):")
if mode == 'e':
message = input("What is your message to encrypt?").encode()
f = Fernet(key)
encrypted = f.encrypt(message)
passkey = open("encryptedmsg.txt", "wb")
passkey.write(encrypted)
passkey.close()
elif mode == 'd':
passread = open("encryptedmsg.txt", "rb")
contents = passread.read()
f = Fernet(key)
decrypted = f.decrypt(encrypted).decode()
print("Decrypted message is ", decrypted)
input()
This is not related to cryptography, but pure Python specific error.
The variable key is assigned in the first 'else' block, line no. 7.
This variable won't available outside that block, unless defined specifically.
More references:
https://docs.python.org/3.8/tutorial/classes.html#class-and-instance-variables
https://docs.python.org/3.8/tutorial/classes.html#private-variables

Python3 - Encrypting and decrypting an image (Fernet) Issue

Good day,
I am doing an assignment for cryptography. It's an easy task I need to take any image, turn it into HEX, encrypt it and then decrypt it.
As I am working in Python and there was no specific encryption method in the task I just use Fernet.
I have an encryptor and decryptor scripts.
Encryption seems to be working because as a test I create a txt document with original HEX and after decryption the program states that original HEX and decrypted one are the same, however the decrypted image is not loading.
Could anyone help out a newbie?
Encryptor:
import binascii
from cryptography.fernet import Fernet
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
key = Fernet.generate_key()
with open('info/key.txt', mode='w+') as keyValue:
keyValue.write(key)
keyValue.seek(0)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='w+') as hexValueFile:
hexValueFile.write(encHexVal)
hexValueFile.seek(0)
a = f.decrypt(encHexVal)
with open('info/realValue.txt', mode='w+') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r') as reading:
realValue = reading.read()
if realValue == a:
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor:
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
hexValue = imageHexValue.read()
a = f.decrypt(hexValue)
with open('info/realValue.txt', mode='r') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == a:
print("All good!")
else:
print("Something is wrong...")
data = a.encode()
data = data.strip()
data = data.replace(' ', '')
data = data.replace('\n', '')
with open('newImage.png', 'wb') as file:
file.write(data)
I am using a random image from the internet of Po from Kung Fu Panda:
The principle problem is that although you hexlify then encrypt in the encryptor you don't unhexlify after decrypting in the decryptor. Its far more common to do things the other way, encrypt then hexlify so that the encrypted binary can be stored in regular text files or sent via http.
You have several problems with trying to write bytes objects to files open in text. I fixed those along the way. But it does leave me puzzled why a file called 'info/encryptedHex.txt' would be binary.
Encryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
(base) td#timpad:~/dev/SO/Encrypting and decrypting in image$ cat de.py
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
encHexValue = imageHexValue.read()
hexValue = f.decrypt(encHexValue)
binValue = binascii.unhexlify(hexValue)
with open('info/realValue.txt', mode='rb') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == hexValue:
print("All good!")
else:
print("Something is wrong...")
with open('newImage.png', 'wb') as file:
file.write(binValue)

Error cryptography Fernet read token from file

I create the key and I encrypt the message send by user, and store this message in a file and after i try to decrypt this message in the file, but i get this error cryptography.fernet.InvalidToken. I don't use the time for the token and I have also converted in byte after.
My code is:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
def encry():
global f
what = input("What i need to encrypt?")
what_b = str.encode(what)
token = f.encrypt(what_b)
print("key generated")
print("encrypted")
file1=open("string.txt", "w")
file1.write(str(token))
file1.close()
file2=open("key.txt", "w")
file2.write(str(key))
file2.close()
def decry():
global f
print("decrypted")
file1=open("string.txt", "r").read()
file_de=str.encode(file1)
file2=open("de.txt", "w")
what_d = f.decrypt(file_de)
file1.close()
file2.write(str(what_d))
file2.close()
choose = input("Do you want, encrypt or decrypt?" + " " + "(e/d)")
if choose == "e":
encry()
elif choose == "d":
decry()
else:
print("Nothing to do")
The problem comes from the way you write and read the message and the key to and from the files. Indeed, the encrypted text and the keys are not strings, but byte strings and need to be treated in a different way.
In your case, when reading and writing it is enough to specify that you do it in binary mode and you can do it by adding the b flag. See the documentation for more detailed information.
Moreover, in your decrypt you also need to read the key from the file.
def encry():
key = Fernet.generate_key()
f = Fernet(key)
what = "example"
what_b = str.encode(what)
token = f.encrypt(what_b)
with open("string.txt", "wb") as f1, open("key.txt", "wb") as f2:
f1.write(token)
f2.write(key)
def decry():
with open("string.txt", "rb") as f1, open("key.txt", "rb") as f2:
token = f1.read()
key = f2.read()
f = Fernet(key)
what_d = str(f.decrypt(token),'utf-8') #converting back to string
encry()
decry()

Categories

Resources