I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!
import hashlib
import mysql.connector
from tkinter import *
from tkinter import messagebox
from cryptography.fernet import Fernet
chat = Tk() #Api I am using to create the GUI for the application
#Connect to MySQL database
try:
loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
retrivedKey = loginFRetrieve.read()
loginFRetrieve.close()
loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
retrivedLC = loginFRetrieve.read()
loginFRetrieve.close()
cipher = Fernet(retrivedKey)
retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
retrivedLC = retrivedLC.decode('utf-8')
lC = retrivedLC.split()
mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
del(lC)
except mysql.connector.Error as err:
chat.withdraw()
messagebox.showerror("Database Error", "Failed to connect to database")
exit()
mycursor = mydb.cursor()
#hashPass hashes and returns a string of characters using SHA-256 algorithm
def hashPass(hP):
shaSignature = \
hashlib.sha256(hP.encode()).hexdigest()
return shaSignature
#userExists checks a database too see if username exists in the database
def userExists(userName):
mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
userResult = mycursor.fetchall()
if userResult:
return True
return False
#Creates a new user in the connected SQL database.
def newUser(nU, nP):
if userExists(nU) == False:
mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
mycursor.fetchall()
r = hashPass(nP)
sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
val = (nU, r)
mycursor.execute(sql, val)
mydb.commit()
chat.title(string="User created")
else:
messagebox.showwarning("User Creation Error", "User already exists")
#Checks the connected SQL database for an existing user.
def existingUser(uN, pW):
if userN.get() != "":
if userExists(uN) == True:
encryptedPass = hashPass(pW)
mycursor.execute("SELECT * FROM logins")
passResult = mycursor.fetchall()
for row in passResult:
if row[1] == uN and row[2] == encryptedPass:
chat.title(string="Login Successful!")
elif row[1] == uN and row[2] != encryptedPass:
messagebox.showerror("Login Error", "Password does not match our records")
else:
messagebox.showerror("Login Error", "User does not exist")
else:
messagebox.showwarning("Login Error", "Please enter a username")
userN? \$\endgroup\$