Variable Is not defined when its actually defined - python

I created a password manager app and I need to encrypt and decrypt the passwords when I use my decrypted variable its shows me that the variable is not defined and I defined it earlier in the code I cant even run the code because of that error If Someone knows how to fix it please help me
here's the link for the code
#My coding skills got you climbing hills
from tkinter import *
import customtkinter
import os
import random
import pyperclip as pc
from tkinter import messagebox as mb
from cryptography.fernet import Fernet
global encrypted
customtkinter.set_appearance_mode("Light")
window=customtkinter.CTk()
# Making all the widgets for thte password saver
window.title("Password saver for me")
window.geometry("750x420")
# Logic (The hard part)
#----------------------------------------------------
def main_func():
#Add Passwords Function
def add():
for i in window.winfo_children():
i.destroy()
password=customtkinter.CTkEntry(window,
width=230
,border_width=0.5
,placeholder_text="Password"
,placeholder_text_color="Silver")
user=customtkinter.CTkEntry(window,
width=230,
border_width=0.5
,placeholder_text="User"
,placeholder_text_color="Silver")
platform_=customtkinter.CTkEntry(window,
width=490,
border_width=0.5
,placeholder_text="Platform"
,placeholder_text_color="Silver")
password.place(x=450,y=35) #I wasn't able to calculate this by myself
user.place(x=192,y=35)
platform_.place(x=192,y=70)
main_func()
def logic():
#Opens the file and writes the user information inside it
#Guardian
if platform_.get() == "" or user.get() == "" or password.get() == "":
mb.showerror("WRONG INPUT","Please Make sure to enter all the fields \nIf you don't have a username/password Enter \'None\'")
return
file = open("pass.txt","a")
write_platform_=file.write("Platform: "+platform_.get()+" | ")
write_email=file.write("Username/Email: "+user.get()+" | ")
write_password=file.write("Password: "+password.get()+"\n")
file.close()
key = Fernet.generate_key()
with open("MyKey.key","wb") as mykey:
mykey.write(key)
############################################ddddddddddddddddddddddddddddddddddddddddddd
with open("MyKey.key","rb") as mykey:
key = mykey.read()
f = Fernet(key)
with open("pass.txt","rb") as original_file:
original = original_file.read()
encrypted = f.encrypt(original)
#########################################3
with open("enc_passwords.txt","wb") as encrypted_file:
encrypted_file.write(encrypted)
f = Fernet(key)
with open("enc_passwords.txt","rb") as encrypted_file:
encrypted=encrypted_file.read()
decrypted=f.decrypt(encrypted)
file=open("pass.txt","wb")
file.write(encrypted)
#Clear Fields
def clear_field():
for i in window.winfo_children():
i.destroy()
add()
def generate_password():
for i in range(12):
a = random.choice("Q!w!E!r!T!y!U!i!O!p!A!s!D!fGhJkLzXcVbNm1234567890")
password.insert(i,a)
pc.copy(password.get())
save=customtkinter.CTkButton(window,text="Save",
command=logic
,fg_color='red',
hover_color="white"
,width=490).place(x=192,y=105)
first_generate_button=customtkinter.CTkButton(window
,width=490
,text="Generate Random Password"
,fg_color="red"
,hover_color="white"
,command=generate_password).place(x=192,y=105+35)
clear_fields=customtkinter.CTkButton(window
,width=490
,text="Clear Fields"
,fg_color="Red"
,hover_color="white"
,command=clear_field).place(x=192,y=105+70)
#--------------------------------------------------------------------------------
def generate():
for i in window.winfo_children():
i.destroy()
main_func()
password_label2=customtkinter.CTkLabel(window,
text="New Password")
password_label2.place(x=191,y=65)
rand_password=customtkinter.CTkEntry(window,
border_width=0.5)
rand_password.place(x=192,y=150-65)
for i in range(12):
a = random.choice("QwErTyUiOpAsDfGhJkLzXcVbNm1234567890")
rand_password.insert(i,a)
pc.copy(rand_password.get())
#---------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------------
#Not finished Need to add encryption
def add_passport():
for i in window.winfo_children():
i.destroy()
name=customtkinter.CTkEntry(window
,placeholder_text="Enter Surname"
,placeholder_text_color="Silver")
passport_no=customtkinter.CTkEntry(window
,placeholder_text="Enter Given name",
placeholder_text_color="Silver")
nation=customtkinter.CTkEntry(window
,placeholder_text="Nationality"
,placeholder_text_color="Silver")
date_of_birth=customtkinter.CTkEntry(window
,placeholder_text="Date of birth"
,placeholder_text_color="Silver")
date_of_issue=customtkinter.CTkEntry(window
,placeholder_text="Date of issue"
,placeholder_text_color="Silver")
authority=customtkinter.CTkEntry(window
,placeholder_text="Authority"
,placeholder_text_color="Silver")
name.place(x=200,y=35)
passport_no.place(x=370,y=35)
nation.place(x=540,y=35)
date_of_birth.place(x=200,y=70)
date_of_issue.place(x=370,y=70)
authority.place(x=540,y=70)
# The space between x + 170 and y supposed to be + 35
main_func()
# platform_: Iphone | Username/Email: Nitay | Password: pro
#All the Buttons
#Saved button
def saved():
file1 = open("pass.txt","rb")
new_window=customtkinter.CTk()
saved_passwords=customtkinter.CTkLabel(new_window,text=decrypted)
saved_passwords.pack()
new_window.mainloop()
return
saved=customtkinter.CTkButton(window,command=saved
,fg_color="red",
hover_color="white",
text="Saved Passwords").place(x=1,y=0)
# Generate password button
#------------------------------------------------------------------------
generate_button=customtkinter.CTkButton(window,text="Generate Password",
command=generate,height=28,
fg_color="red",
hover_color="white").place(x=1,y=35)
#------------------------------------------------------------------------
#Save button
#-------------------------------------------------
add_password=customtkinter.CTkButton(window
,text="Add Password"
,fg_color="red"
,hover_color="white"
,command=add).place(x=1,y=70)
#-------------------------------------------------
#Add Password Button
add_passports=customtkinter.CTkButton(window,text="Add Passport"
,fg_color="red"
,hover_color="white"
,command=add_passport).place(x=1,y=105)
#Main Loop
main_func()
window.mainloop()

Related

Spent like an hour trying to fix this I'm getting no where someone please help.. python

from tkinter import *
from tkinter import messagebox
w=Tk()
w.geometry('350x500')
w.title('Sunset Panel')
w.resizable(0,0)
#Making gradient frame
j=0
r=10
for i in range(100):
c=str(222222+r)
Frame(w,width=10,height=500,bg="#"+c).place(x=j,y=0)
j=j+10
r=r+1
Frame(w,width=250,height=400,bg='white').place(x=50,y=50)
l1=Label(w,text='Username',bg='white')
l=('Consolas',13)
l1.config(font=l)
l1.place(x=80,y=200)
#e1 entry for username entry
e1=Entry(w,width=20,border=0)
l=('Consolas',13)
e1.config(font=l)
e1.place(x=80,y=230)
#e2 entry for password entry
e2=Entry(w,width=20,border=0,show='*')
e2.config(font=l)
e2.place(x=80,y=310)
l2=Label(w,text='Password',bg='white')
l=('Consolas',13)
l2.config(font=l)
l2.place(x=80,y=280)
###lineframe on entry
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=332)
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=252)
from PIL import ImageTk,Image
imagea=Image.open("log.png")
imageb= ImageTk.PhotoImage(imagea)
label1 = Label(image=imageb,
border=0,
justify=CENTER)
label1.place(x=115, y=50)
#Command
def cmd():
db = open("Data.txt", "r")
Username = e1
Password = e2
if Username == e1:
d = []
f = []
for i in db:
a,b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
if e1.get() == data[Username] and e2.get() == data[Password]:
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
#Button_with hover effect
def bttn(x,y,text,ecolor,lcolor):
def on_entera(e):
myButton1['background'] = ecolor #ffcc66
myButton1['foreground']= lcolor #000d33
def on_leavea(e):
myButton1['background'] = lcolor
myButton1['foreground']= ecolor
myButton1 = Button(w,text=text,
width=20,
height=2,
fg=ecolor,
border=0,
bg=lcolor,
activeforeground=lcolor,
activebackground=ecolor,
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=x,y=y)
bttn(100,375,'L O G I N','white','#994422')
w.mainloop()
my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ezneu\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\ezneu\OneDrive\Desktop\login\login.py", line 80, in cmd
if e1.get() == data[Username] and e2.get() == data[Password]:
KeyError: <tkinter.Entry object .!entry>
sorry for the dumb question ive been at this all day and cant seem to figure out what the problem is I sent the entire code above if someone can correct! I keep getting the same " KeyError: <tkinter.Entry object .!entry>" no clue what this means but I even watched a tutorial and my code was almost the same as the person in the tut yet there worked perfect please help!
Since Username is a reference to an Entry widget and data is a dictionary with string as the keys, so data[Username] will raise the exception.
Your checking should test whether e1.get() is a key in data and e2.get() should be equal to data[e1.get()].
Below is the suggested modification of cmd():
def cmd():
username = e1.get().strip()
password = e2.get().strip()
# both username and password have been input?
if username and password:
# load the credentials as a dictionary
with open("Data.txt") as db:
data = {}
for i in db:
a, b = i.split(", ")
data[a] = b.strip()
# check username and password
if username in data and data[username] == password:
messagebox.showinfo("Login Success", "Welcome")
# do whatever you want if login successful
else:
messagebox.showwarning("Login Failed", "Try again")
else:
messagebox.showwarning("Invalid", "Please enter both username and password")
https://realpython.com/python-keyerror/ :
A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary ( in your case data ).
Here an example of content of the file 'Data.txt':
adam, a
bogdan, b
cicero, c
daniel, d
Below a making sense code of cmd() running without the error message:
def cmd():
db = open("Data.txt", "r")
d = []
f = []
for i in db.readlines():
print (i)
a, b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
print(data)
try:
if data[e1.get()] == e2.get():
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Wrong password entered", "Try again")
except KeyError:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
And here entire code with the gradient frame which looks like it should:
from tkinter import *
w=Tk()
w.geometry('350x500')
w.title('Sunset Panel')
w.resizable(0,0)
#Making gradient frame
j=0; r=10
for _ in range(35):
c=str(f'{155-r:02x}{255-r:02x}{155-r:02x}')
print(c,end='|')
Frame(w,width=10,height=500,bg="#"+c).place(x=j,y=0)
j=j+10
r=r+3
Frame(w,width=250,height=400,bg='white').place(x=50,y=50)
l1=Label(w,text='Username',bg='white')
l=('Consolas',13)
l1.config(font=l)
l1.place(x=80,y=200)
#e1 entry for username entry
e1=Entry(w,width=13,border=0)
l=('Consolas',13)
e1.config(font=l)
e1.place(x=80,y=230)
#e2 entry for password entry
e2=Entry(w,width=13,border=0,show='*')
e2.config(font=l)
e2.place(x=80,y=310)
l2=Label(w,text='Password',bg='white')
l=('Consolas',13)
l2.config(font=l)
l2.place(x=80,y=280)
###lineframe on entry
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=332)
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=252)
from PIL import ImageTk,Image
imagea=Image.open("log.png")
imageb= ImageTk.PhotoImage(imagea)
label1 = Label(image=imageb, border=0, justify=CENTER)
label1.place(x=115, y=50)
#Command
def cmd():
db = open("Data.txt", "r")
d = []
f = []
for i in db.readlines():
print (i)
a, b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
print(data)
try:
if data[e1.get()] == e2.get():
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Wrong password entered", "Try again")
except KeyError:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
#Button_with hover effect
def bttn(x,y,text,ecolor,lcolor):
def on_entera(e):
myButton1['background'] = ecolor #ffcc66
myButton1['foreground']= lcolor #000d33
def on_leavea(e):
myButton1['background'] = lcolor
myButton1['foreground']= ecolor
myButton1 = Button(w,text=text,
width=20,
height=2,
fg=ecolor,
border=0,
bg=lcolor,
activeforeground=lcolor,
activebackground=ecolor,
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=x,y=y)
bttn(100,375,'L O G I N','white','#994422')
w.mainloop()

How do I test functions using pytest

Hello,
I need your help writing test functions for the following functions using pytest: add_new_user, register_user, login_verify
I am trying to test my login system program using the pytest module which is a requirement for the end-semester project. The following are functions I am having trouble testing:
Function without parameters, but rather get information from the user.
Function that appends information to a text file.
Function that reads from a text file.
Thank you in advance to the good samaritan.
1a) Python File.
def add_new_user():
"""The function enables the users to enter their information and register"""
# Gobal variables
global username
global password
global fullname
global username_entry
global password_entry
global fullname_entry
global new_user_window
# Creates another window on top of the main menu window
# for the user to enter their information.
new_user_window = Toplevel(main_window)
new_user_window.title("New User")
new_user_window.geometry("300x300")
# Create a string variable that corresponds to the user's
# username, password and full name
username = StringVar()
password = StringVar()
fullname = StringVar()
# Create "fill information" label.
label2 = Label(new_user_window, text = "Please fill in the info below", bg="gray", fg="pink")
label2.pack(fill=X, pady=20)
# Create username's label and the entry box for a user input
user_info_panel = Frame(new_user_window)
user_info_panel.pack(pady=20)
username_label=Label(user_info_panel, text="Username: ")
username_label.grid(row=0, column=0)
username_entry = Entry(user_info_panel, textvariable=username)
username_entry.grid(row=0, column=1)
# Create space between the username and password
Label(user_info_panel, text="").grid(row=1)
# Create password's label and the entry box for a user input
password_label = Label(user_info_panel, text="Password: ")
password_label.grid(row=2, column=0)
password_entry = Entry(user_info_panel, textvariable=password)
password_entry.grid(row=2, column=1)
# Create space between password and full name
Label(user_info_panel, text="").grid(row=3)
# Create full name's label and an entry box for the user input
fullname_label = Label(user_info_panel, text="Full name: ")
fullname_label.grid(row=4, column=0)
fullname_entry = Entry(user_info_panel, textvariable=fullname)
fullname_entry.grid(row=4, column=1)
# Create registration button for the user to their information.
register_btn = Button(new_user_window, text="Register", command=register_user)
register_btn.pack()
b) Test file
def test_add_new_user():
"""Verify that the add_new_user function works correctly.
Parameters: none
Return: nothing
"""
assert add_new_user("username") == "Fred69_Coder"
assert add_new_user("password") == "#123kitoVu"
assert add_new_user("fullname") == "Fred Okorio"
2a) Python file
def register_user():
"""The function writes the user's confidential information in a text file"""
# Initialize the False boolean variable
registered = False
# Get the information typed by the user in the entry boxes.
username_text = username.get()
password_text = password.get()
name_text = fullname.get()
try:
# Create the credentials text file and append the new user information
# in the already existing file.
with open("credentials.txt", "a") as credentials:
# Open the credential text file for reading and store a reference
# to the opened file in a variable named text_file.
with open("credentials.txt", "r") as text_file:
# Read the contents of the text
# file one line at a time.
for line in text_file:
# Split the data in line variable and store the split
# data in the login_info variable.
login_info = line.split()
# From all the information in the data base extract
# username information.
if username_text == login_info[1]:
registered = True
# If the user is already registered
if registered:
# Clear the user entry boxes
username_entry.delete(0, END)
password_entry.delete(0, END)
fullname_entry.delete(0, END)
# For debugging purpose
print("user already exist")
# Window for a failed login process.
failed_registration_window = Toplevel(new_user_window)
failed_registration_window.geometry("200x200")
failed_registration_window.title("warning!")
Label(failed_registration_window, text="user already exists.",
bg="gray", fg="pink").pack(fill=X, pady=20)
# Ok button exits the window
ok_btn = Button(failed_registration_window, text="Please login",
width="20",command=lambda:failed_registration_window.destroy())
ok_btn.pack(pady=20)
else:
credentials.write("Username: "+ username_text + " " + "Password: " + password_text + " " +"Name: "+ name_text + "\n")
# Clear the user entry boxes.
username_entry.delete(0, END)
password_entry.delete(0, END)
fullname_entry.delete(0, END)
# Window for a successful login process.
successful_registration_window = Toplevel(new_user_window)
successful_registration_window.geometry("200x200")
successful_registration_window.title("Success!")
Label(successful_registration_window, text="Sucessfully
Registered!", bg="gray", fg="pink").pack(fill=X, pady=20)
ok_btn = Button(successful_registration_window, text="OK", width="20", command = lambda:successful_registration_window.destroy())
ok_btn.pack(pady=20)
except FileNotFoundError as not_found_err: print(not_found_err)
except PermissionError as perm_err: print(perm_err)
b) Test file
def test_register_user():
"""Verify that the register_user function works correctly.
Parameters: none
Return: nothing
"""
3a) Python file
def login_verify():
try:
user = username_verify.get()
password = password_verify.get()
login = False
# Open the credential text file for reading and store a reference
# to the opened file in a variable named text_file.
with open("credentials.txt", "r") as text_file:
# Read the contents of the text
# file one line at a time.
for line in text_file:
login_info = line.split()
if user == login_info[1] and password == login_info[3]:
login = True
if login:
label1 = Label(login_window, text = "You've logged in successfully", fg="green")
label1.pack()
else:
failed_login_window = Toplevel(login_window)
failed_login_window.geometry("200x200")
failed_login_window.title("Warning!")
Label(failed_login_window, text="Invalid username. Please register", bg="gray", fg="pink").pack(fill=X, pady=20)
ok_btn = Button(failed_login_window, text="OK", width="20", command= lambda:failed_login_window.destroy())
ok_btn.pack(pady=20)
except IndexError as index_err:
print(index_err)
except FileNotFoundError as not_found_err:
print(not_found_err)
except PermissionError as perm_err:
print(perm_err)
b) Test file
def test_login_verify():
"""Verify that the login_verify function works correctly.
Parameters: none
Return: nothing
"""

Tkinter socket sending data error while opening the server and client

Got an error of: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied when using socket with tkinter on login between server and client
Server :
import socket
import pickle
import datetime
# Socket settings
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket setting
my_socket.bind(('0.0.0.0', 1024)) # binding the server ip
my_socket.listen(10) # how much people can join the server
client_socket, client_address = my_socket.accept() # accepting the people if the server is available
print("Server Open") # prints that the server is open
# Functions
def get_users():
# get from the login_users.txt all users & passwords
# format in file - username|password
logs = []
with open('login_users.txt', 'r') as f:
for line in f:
cur = line.strip('\n\r')
cur = cur.split("|")
logs.append(cur)
f.close()
return logs
def get_rank(user):
# get from the ranks.txt all users & passwords
# format in file - username|password
ranks = []
with open('ranks.txt', 'r') as f:
for line in f:
cur = line.strip('\n\r')
cur = cur.split("|")
ranks.append(cur)
f.close()
for r in ranks:
if r[0] == user:
return r[1]
def add_to_logs(user, line):
# add attempt to record (logs_.txt)
now = datetime.datetime.now()
with open('logs_.txt', 'a') as f:
f.write(line + " " + str(now) + "\n")
f.close()
def user_exist(user):
for log in logs:
if log[0] == user:
return True
def check(user, password):
# check the password that the user typed
# if there are 3 failed tried disable the login button
global logs
global atmp
global null_state
global login_state
global logged_user
global status
# get text from boxes:
user = user.get()
password = password.get()
print("user: ", user)
print("pass: ", password)
# add attempt to logs_ file
add_to_logs(user, f"{user} has tried to log in.")
atmp += 1
if user_exist(user):
null_state = False
for log in logs:
if log[0] == user and log[1] == password:
# pop up login succeed
login_state = True
logged_user = user
status = True
if __name__ == '__main__':
btpressed = pickle.loads(my_socket.recv(1024))
if btpressed:
client_socket.send(pickle.dumps([status]))
username, password = pickle.loads(my_socket.recv(1024)) # Getting data from the server
status = check(username, password)
print(status)
client:
import socket
import pickle
import tkinter as tk
import tkinter.messagebox as mb
import tkinter.font as tkFont
user_send = "nothing"
pass_send = "nothing"
# Socket settings
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # setting the socket
my_socket.connect(('127.0.0.1', 1024)) # joining the server
print("Connected to the server successfully!")
def check_null(user, password):
global null_state
# check for the username and password in the file:
if user == "" or password == "" or user == "" and password == "":
null_state = True
fail_msg = "Please make sure you have entered username and password in both fields!"
mb.showinfo(title="Enter username and password", message=fail_msg)
#def display_system():
#root1.title("Secure4U")
#root1.geometry("1200x600")
#fontStyle = tkFont.Font(family="Lucida Grande", size=20)
#show_user_logged = tk.Label(root1, text="Hello " + logged_user + ",", font=fontStyle)
#show_user_logged.pack(side="top", anchor="nw")
#user_rank =
#show_user_rank = tk.Label(root1, text="Rank: " + str(user_rank), font=fontStyle)
#show_user_rank.pack(side="top", anchor="nw")
#root1.mainloop() # run tkinter display
def display_login():
global log_button
# initiate and display all objects on screen
root.title("Secure4U Login")
root.geometry("450x250")
fontStyle = tkFont.Font(family="Lucida Grande", size=20)
# user name
user_label = tk.Label(root, text="Username:", font=fontStyle)
# user_box = tk.Text(root, bg="grey", height=1, width=20, font=fontStyle)
user_box = tk.Entry(root, bg="grey", font=fontStyle)
user_label.pack()
user_box.pack()
# password
pass_label = tk.Label(root, text="Password:", font=fontStyle)
# pass_box = tk.Text(root, bg="grey", font=fontStyle)
pass_box = tk.Entry(root, bg="grey", font=fontStyle, show="*")
pass_label.pack()
pass_box.pack()
# login button
log_button = tk.Button(root, text='Login', height=2, width=20, command=lambda:(button_pressed()))
log_button.pack()
user_send = user_box
pass_send = pass_box
root.mainloop() # run tkinter display
def button_pressed():
BtPressed = True
if __name__ == '__main__':
global BtPressed
BtPressed = False
status = False
my_socket.send(pickle.dumps([BtPressed]))
if not status:
null_state = False # checks if the user entered null data on one or both of the fields
root = tk.Tk()
display_login()
if BtPressed:
my_socket.send(pickle.dumps([user_send, pass_send])) # Sending data to the server
status = pickle.loads(my_socket.recv(1024)) # Getting data from the server
# success_msg = f"Hello {logged_user}, you logged in successfully!"
# mb.showinfo(title="login succeed!", message=success_msg)
I don't know what it happened and I tried everything, please help me if you can
Thank you :)

why am I getting cryptography fernet InvalidToken when using the same key

Hello so I am making a password manager and I want to encrypt the password file, so I generate and create the first password and when I read it and decrypt it reads it. And then when making another password it creates it but then when decrypting it throws an error. From what I can see I am using the same key.
Here is the code:
#imports
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
saltfile.close()
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
return passwordOut
#Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
mykey.close()
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
mykey.close()
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
password_file.close()
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
password_file.close()
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','rb') as password_file:
read = password_file.read()
decrypt = f.decrypt(read)
print(decrypt)
password_file.close()
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')
Here is the terminal code:
C:\Users\James\Documents\passwords\venv\Scripts\python.exe C:/Users/James/Documents/passwords/main.py
True
Hello and welcome to your password manager!
Enter your username james
Enter your password: Kaits_1204
Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit
Enter a number from the menu: 2
Traceback (most recent call last):
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 119, in _verify_signature
h.verify(data[-32:])
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 74, in verify
ctx.verify(signature)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 75, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/James/Documents/passwords/main.py", line 106, in <module>
decrypt = f.decrypt(read)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 80, in decrypt
return self._decrypt_data(data, timestamp, time_info)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 137, in _decrypt_data
self._verify_signature(data)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 121, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
Process finished with exit code 1
The problem is that you take input of user for chosen account password then you append splitter and random generated password then '/n'. After that you encrypt this var using fernet. This method will work to view your first password since with first password you read and decrypt whole file but not with multiple encrypted passwords since each var encryption is unique (having different IV) which means that to decrypt all the passwords you will need a way to signal the end of an encrypted password and beginning of another encrypted password so that you pass to ferent the correct ciphertext with correct margins. This can be done by simply adding --END OF PASSWORD-- after each encryption write to password file. Then during reading of passwords you can just split pass file on these margins and pass result to fernet.
NOTE: dont use this code as your password manager since although you encrypt your passwords you are leaving your master password in mykey.key unencrypted which makes this totally useless.
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
#saltfile.close() # You dont need to close
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
# return passwordOut
# Random Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
#mykey.close() # with doesnt need file to be closed
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
print("File ", file)
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','r') as password_file:
whole_file = password_file.read()
password_list = whole_file.split("--END OF PASSWORD--")
for password in password_list:
if password:
decrypt = f.decrypt(bytes(password, encoding="utf-8"))
print("Decrypted pass: ", decrypt)
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')

Why does my function not execute when the condition is met?

I'm trying to make a login form for my server application and have stumbled onto an invisible error (the worst kind). I have a tries variable that increments by 1 every time the user enters the username incorrectly. When the tries variable reaches 3, the program should then execute the block() function. My issue is that it doesn't.
All my .txt files are blank so there's not an error there and everything seems fine. Please help because I'm pulling my hair out!
Here's the code:
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#create black list
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
os.remove('ipBlackList.txt')
print('\nYour account has been re-enabled. You may log in
now.')
time.sleep(2)
t = 60
countdown(int(t))
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
username = input("\nUsername: ")
#check if username exists
usernames = open("usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()
In fact, your code do execute the block() function when tries==3, but in the begining of the block() you recreate the black list file, then you read the empty file and as a result the condition if ipBlock in isBlocked: is always false.
So, I've placed the commands that create the file out of the block(). Also, I've changed the remove of the black list file in the countdown() function and recreate but not delete it, because your code try to read it again when restarts to ask the username. Also I've set tries == 0 when block() ends. Also, the indentation at the end of countdown() was incorrect.
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please \
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
#os.remove('ipBlackList.txt')
# Recreate an empty black list file
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
print('\nYour account has been re-enabled. You may log in \
now.')
time.sleep(2)
t = 6
countdown(int(t))
#create black list file (empty)
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
tries = 0
username = input("\nUsername: ")
#check if username exists
usernames = open("/test/usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()

Categories