I am working on a piece of code which takes an input, writes it to a text file then reads the text file, decrypts it and prints the output. Everything is working except for the decrypt part of my code. I have two linescommented out above. They were also producing errors which led me to believe it is a problem with my decryption.
import cryptography
from cryptography.fernet import Fernet
import os
import os.path
doc = open("cryptest.txt", "a+")
query = input('Type the text to be encrypted:').encode('utf-8')
print(query + ' is the query'.encode('utf-8'))
key = Fernet.generate_key()
f = Fernet(key)
cipher_text = f.encrypt(query)
#plain_text = f.decrypt(query)
#plain_text = f.decrypt(cipher_text)
doc.write("\n" + str(cipher_text))
doc.close() #closes file
open1 = open("cryptest.txt", "r") #opens file to read it
#open2 = open1.encode('utf-8')
print(open1.read() + 'is the contents of the text document')
#print (f.decrypt(open2.read())) #prints whatever is in the text file
plaint = open1.read().encode('utf-8')
print(plaint +'is the encoded contents of the file'.encode('utf-8'))
decrypto = f.decrypt(plaint)
print(str(decrypto) + 'is the decrypted information'.encode('utf-8'))
doc.close()
The error I am getting is as follows
Traceback (most recent call last):
File ".\CryptoTut.py", line 25, in <module>
decrypto = f.decrypt(plaint)
File "C:\Program Files (x86)\Python36-32\lib\site-
packages\cryptography\fernet.py", line 74, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Program Files (x86)\Python36-32\lib\site-
packages\cryptography\fernet.py", line 88, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
Related
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")
I am working on AZURE Cognitive API Search. While getting the result from API, I want to write it into a new JSON File. I tried to access the analyse_result variable with the line but it does not work. It shows that the object is not JSON Serializable. My code is-
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from array import array
import os
from PIL import Image
import sys
import time
import json
import csv
subscription_key = ""
endpoint = ""
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
def azure_ocr_api(): #image_url
local_image_url = r"E:\Bank of Baroda\BOB IMAGE\Cheque309086.jpeg"
# read_response = computervision_client.read_in_stream(open("./Images/" + image_url,'rb'), raw=True)
read_response = computervision_client.read_in_stream(open(local_image_url,'rb'), raw=True)
# Get the operation location (URL with an ID at the end) from the response
read_operation_location = read_response.headers["Operation-Location"]
# Grab the ID from the URL
operation_id = read_operation_location.split("/")[-1]
# Call the "GET" API and wait for it to retrieve the results
while True:
read_result = computervision_client.get_read_result(operation_id)
if read_result.status not in ['notStarted', 'running']:
break
time.sleep(1)
list = []
if read_result.status == OperationStatusCodes.succeeded:
for text_result in read_result.analyze_result.read_results:
for line in text_result.lines:
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(line, f, ensure_ascii=False, indent=4)
# print(list)
# pass
# return list
azure_ocr_api()
print("End of Computer Vision quickstart.")
The code shows a error like this -
Traceback (most recent call last):
File "e:\Bank of Baroda\m.py", line 44, in <module>
azure_ocr_api()
File "e:\Bank of Baroda\m.py", line 40, in azure_ocr_api
json.dump(line, f, ensure_ascii=False, indent=4)
File "C:\Users\Clasher\anaconda3\lib\json\__init__.py", line 179, in dump
for chunk in iterable:
File "C:\Users\Clasher\anaconda3\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Users\Clasher\anaconda3\lib\json\encoder.py", line 179, in default
TypeError: Object of type Line is not JSON serializable
Please help.
I'm developing too to compare database schema of Test and Prod database.
I can succesfully compare schema and print to command line.
However I don't know how to store results to JSON, CSV file or any file. Please advice!
from pprint import pprint
from sqlalchemydiff import compare
from sqlalchemy.engine import URL
import pyodbc
import time
# Pass through Pyodbc string
conn_string_dw_test = "DRIVER=..."
conn_string_dw_prod = "DRIVER=..."
connection_url_dw_test = URL.create("mssql+pyodbc", query={"odbc_connect": conn_string_dw_test})
connection_url_dw_prod = URL.create("mssql+pyodbc", query={"odbc_connect": conn_string_dw_prod})
print('')
print('-----SCHEMA COMPARE FOR TEST AND PROD DW-----')
result_dw = compare(connection_url_dw_test, connection_url_dw_prod)
if result_dw.is_match:
print('')
print('DW Schemas are identical')
print('')
else:
print('')
print('We detected following differences')
print('DW Test is on Left. DW Prod is on Right')
print('')
pprint(result_dw.errors)
# Export CSV
filename = "SchemaCompareReports\SchemaCompareReport_" + time.strftime("%Y%m%d-%H%M%S") + ".csv"
result_dw.to_csv(filename) # NOT WORKING
print("Report exported: " + filename)
ERROR in first try:
traceback (most recent call last):
File ".\SchemaComparePOC.py", line 74, in
result_dw.to_csv(filename)
AttributeError: 'CompareResult' object has no attribute 'to_csv'
I also tried in second try to save results to json file, but got error:
filename = "SchemaCompareReport_DW_" + time.strftime("%Y%m%d-%H%M%S") + ".json"
a_file = open(filename, "w")
json.dump(result_dw.dump_errors, a_file)
a_file.close()
Error of second try:
Traceback (most recent call last):
File "./SchemaComparePOC.py", line 106, in <module>
json.dump(result_dw.dump_errors, a_file)
File "C:\Python\Python3.8.9\lib\json\__init__.py", line 179, in dump
for chunk in iterable:
File "C:\Python\Python3.8.9\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Python\Python3.8.9\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type method is not JSON serializable
In third try I got no error, but file was empty:
filename = "SchemaCompareReport" + time.strftime("%Y%m%d-%H%M%S") + ".json"
a_file = open(filename, "w")
json.dump(result_dw.dump_errors.__dict__, a_file)
a_file.close()
Programming language: Python
i have three files, one is to generate the key, 2nd is to encrypt, and the other is to decrypt.. the 1st and the 2nd files work.. but the decrypt file won't work
generate key file:
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
generate_key()
encrypt file -
from cryptography.fernet import Fernet
def load_key():
return open("secret.key", "rb").read()
def encrypt_message(message):
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
EncryptedTextWriteFile = open("encrypt.txt", "r+")
EncryptedTextWriteFile.write(str(encrypted_message))
notEncryptedFile = open("text.txt", "r")
notEncryptedText = notEncryptedFile.read()
if __name__ == "__main__":
encrypt_message(notEncryptedText)
notEncryptedFile.close()
Decrypt file -
from cryptography.fernet import Fernet
def load_key():
return open("secret.key", "rb").read()
def decrypt_message(encrypted_message):
key = load_key()
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
shit = decrypted_message.decode()
print(shit)
DencryptedTextWriteFile = open("decrypt.txt", "r+")
DencryptedTextWriteFile.write(shit)
EncryptedFile = open("decrypt.txt", "r")
EncryptedText = EncryptedFile.read()
if __name__ == "__main__":
decrypt_message(EncryptedText)
the string i tried - ( this test is in the text.txt )
hirusha
the error i get:
Traceback (most recent call last):
File "d:/development/Python/Everything/Releases/0.2/Build 02/_Releases/Encoder and Decoder/decrypt.py", line 27, in <module>
decrypt_message(EncryptedText)
File "d:/development/Python/Everything/Releases/0.2/Build 02/_Releases/Encoder and Decoder/decrypt.py", line 15, in decrypt_message
decrypted_message = f.decrypt(encrypted_message)
File "C:\Users\hirusha\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\fernet.py", line 75, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Users\hirusha\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\fernet.py", line 100, in _get_unverified_token_data
utils._check_bytes("token", token)
File "C:\Users\hirusha\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\utils.py", line 29, in _check_bytes
raise TypeError("{} must be bytes".format(name))
TypeError: token must be byte
The problem is that when you open the file decrypt.txt and read the file, it gets converted into string. But the .decrypt function only accepts input in byte.
I think this should solve your problem:
Generates a key and stores it in key.key file:
from cryptography.fernet import Fernet
def write_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
write_key()
Encrypts a file and stores it in enc_text.txt file:
from cryptography.fernet import Fernet
with open("key.key","rb") as f:
key=f.read()
f = Fernet(key)
with open('text.txt', 'rb') as original_file:
original = original_file.read()
encrypted = f.encrypt(original)
with open ('enc_text.txt', 'wb') as encrypted_file:
encrypted_file.write(encrypted)
Decrypts the enc_text.txt file and writes the output in decrypt.txt
from cryptography.fernet import Fernet
with open("key.key","rb") as f:
key=f.read()
f = Fernet(key)
with open('enc_text.txt', 'rb') as encrypted_file:
encrypted = encrypted_file.read()
decrypted = f.decrypt(encrypted)
with open('decrypt.txt', 'wb') as decrypted_file:
decrypted_file.write(decrypted)
Sujay's answer was posted while I was writing this one. It is correct, but I still wanted to post this to perhaps give some more insight into what this means.
Most (if not all) encryption tools work on bytes, not str. This is both because these days encrypting binary (non-string) data is more common, and because the encryption algorithms work on numbers, and bytes are strings of numbers in range(0, 256).
In the decryption program, you are loading the ciphertext in this line:
EncryptedFile = open("decrypt.txt", "r")
Contrast this to how you load the encryption key:
def load_key():
return open("secret.key", "rb").read()
The difference is the mode parameter to open: if there is a b in the string, it means it operates in binary mode, working on bytes rather than str. Here's an example:
>>> text = open('test.txt', 'r').read()
>>> text
'Hello World!\n'
>>> binary = open('test.txt', 'rb').read()
>>> binary
b'Hello World!\n'
>>> type(text)
<class 'str'>
>>> type(binary)
<class 'bytes'>
This distinction is important because str represents character sequences, and those can be encoded into binary in vastly different ways. Which of these you choose will affect what ones and zeros go into the encryption algorithm, and consequently what comes out.
The reason the encryption program worked, despite also reading the plaintext file in text mode, is because of this line:
encoded_message = message.encode()
str.encode converts the string into bytes using the encoding supplied, or the default one (usually UTF-8) if it is not specified. The bytes.decode method, seen in the decryption program, does the opposite: it converts bytes to str.
>>> text = '稲妻の腕を借らん草枕'
>>> text.encode()
b'\xe7\xa8\xb2\xe5\xa6\xbb\xe3\x81\xae\xe8\x85\x95\xe3\x82\x92\xe5\x80\x9f\xe3\x82\x89\xe3\x82\x93\xe8\x8d\x89\xe6\x9e\x95'
>>> text.encode('utf-16')
b'\xff\xfe2z\xbbYn0U\x81\x920\x1fP\x890\x930I\x83\x95g'
>>> u16_data = text.encode('utf-16')
>>> u16_data.decode('utf-16')
'稲妻の腕を借らん草枕'
>>> u16_data.decode() # this is why specifying the encoding is important
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
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