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")
Related
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
i'm a noob to programming and i keep getting this error while using the vedere() function. Sorry if it's a stupid question but i am totally new to python and to this forum. Also sorry if some part of the code is in italian. Btw it's a very basic password manager with some encryption for the passwords, here is the code:
import pyfiglet
from cryptography.fernet import Fernet
r = pyfiglet.figlet_format("Petrux Passwd Manager", font="slant")
print(r)
'''def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as k:
k.write(key)'''
def load_key():
file = open("key.key", "rb")
key = file.read()
file.close()
return key
pwd = input("Inserisci la pswd master:\n")
key = load_key() + pwd.encode()
fernet = Fernet(key)
def aggiungi():
dominio = input("Dominio:\n")
email = input("Email o username:\n")
passwd = input("Password:\n")
with open("5f4dcc3b5aa765d61d8327deb882cf99.txt", "a") as f:
f.write(dominio + "|" + email + "|" + fernet.encrypt(passwd.encode()).decode() + "\n")
print("Credenziali aggiunte con successo!")
def vedi():
with open("5f4dcc3b5aa765d61d8327deb882cf99.txt", "r") as f:
for line in f.readlines():
data = line.rstrip()
dominio, user, passw = data.split("|")
print("Dominio: ", dominio,"User: ", user, "| Password: ",
fernet.decrypt(passw.encode()).decode())
while True:
if pwd == "p3truxx":
mode = input("Vuoi aggiungere una password o vedere le esistenti?\n(aggiungere/vedere)\n \nOppure scrivi q per uscire\n").lower()
if mode == "vedere":
vedi()
elif mode == "aggiungere":
aggiungi()
elif mode == "q":
quit()
else:
print("Input non valido coglione")
else:
print("Password sbagliata")
continue
And here is the error:
Traceback (most recent call last):
File "C:\Users\invic\PycharmProjects\adventure\main.py", line 43, in <module>
vedi()
File "C:\Users\invic\PycharmProjects\adventure\main.py", line 35, in vedi
dominio, user, passw = data.split("|")
ValueError: not enough values to unpack (expected 3, got 1)
Thanks to an user who responded in the comment i tried to create a new file with the same code and worked just fine.
Probably the older .txt file contains some line that doesn't have a "|".
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
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
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