🛡️ A Python-based password manager designed to help users securely store and manage their passwords with Advanced Encryption techniques.🔒
import tkinter as tk
from tkinter import messagebox
import mysql.connector
from mysql.connector import Error
import bcrypt

class PasswordManagerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("CryptWizard V1.0")
        self.root.geometry("400x300")

        self.db_connection = self.connect_to_database()

        self.create_widgets()

    def connect_to_database(self):
        try:
            connection = mysql.connector.connect(
                host="localhost",
                user="root",
                password="asdf",
                database="passwordmanager"
            )
            if connection.is_connected():
                return connection
        except Error as e:
            print("\nError connecting to the database:", e)
        return None

    def create_widgets(self):
        self.label = tk.Label(self.root, text="Crypt Wizard", font=("Helvetica", 16))
        self.label.pack(pady=20)

        self.register_button = tk.Button(self.root, text="Register", command=self.register_user)
        self.register_button.pack()

        self.login_button = tk.Button(self.root, text="Login", command=self.user_login)
        self.login_button.pack()

        # self.view_users_button = tk.Button(self.root, text="List of Users", command=self.view_users)
        # self.view_users_button.pack()

        self.exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
        self.exit_button.pack()

    def register_user(self):
        self.register_window = tk.Toplevel(self.root)
        self.register_window.title("Register")
        self.register_window.geometry("300x200")

        self.register_label = tk.Label(self.register_window, text="Register", font=("Helvetica", 16))
        self.register_label.pack(pady=10)

        self.username_label = tk.Label(self.register_window, text="Username:")
        self.username_label.pack()

        self.username_entry = tk.Entry(self.register_window)
        self.username_entry.pack()

        self.password_label = tk.Label(self.register_window, text="Password:")
        self.password_label.pack()

        self.password_entry = tk.Entry(self.register_window, show="*")
        self.password_entry.pack()

        self.register_button = tk.Button(self.register_window, text="Register", command=self.add_user)
        self.register_button.pack(pady=10)

    def add_user(self):
        username = self.username_entry.get()
        password = self.password_entry.get()

        if not username or not password:
            messagebox.showerror("Error", "Please fill in all fields.")
            return

        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(password.encode(), salt)

        try:
            cursor = self.db_connection.cursor()
            query = "INSERT INTO Users (username, salt, master_key) VALUES (%s, %s, %s)"
            cursor.execute(query, (username, salt.decode(), hashed_password.decode()))
            self.db_connection.commit()
            messagebox.showinfo("Success", "User registered successfully!")
            self.register_window.destroy()
        except Error as e:
            messagebox.showerror("Error", f"Registration failed: {e}")



    def user_login(self):
        self.login_window = tk.Toplevel(self.root)
        self.login_window.title("Login")
        self.login_window.geometry("300x250")

        self.login_label = tk.Label(self.login_window, text="Login", font=("Helvetica", 16))
        self.login_label.pack(pady=10)

        self.username_label = tk.Label(self.login_window, text="Username:")
        self.username_label.pack()

        self.username_entry = tk.Entry(self.login_window)
        self.username_entry.pack()

        self.password_label = tk.Label(self.login_window, text="Password:")
        self.password_label.pack()

        self.password_entry = tk.Entry(self.login_window, show="*")
        self.password_entry.pack()

        self.login_button = tk.Button(self.login_window, text="Login", command=self.authenticate_user)
        self.login_button.pack(pady=10)



    def authenticate_user(self):
        username = self.username_entry.get()
        password = self.password_entry.get()

        if not username or not password:
            messagebox.showerror("Error", "Please fill in all fields.")
            return

        try:
            cursor = self.db_connection.cursor()
            query = "SELECT id, salt, master_key FROM Users WHERE username = %s"
            cursor.execute(query, (username, ))
            result = cursor.fetchone()

            if result:
                user_id, salt, stored_master_key = result
                user_master_key = bcrypt.hashpw(password.encode(), salt.encode())

                if user_master_key == stored_master_key.encode():
                    messagebox.showinfo("Success", "Login successful!")
                    self.login_window.destroy()
                    self.show_passwords(user_id)
                else:
                    messagebox.showerror("Error", "Authentication failed. Incorrect username or password.")
            else:
                messagebox.showerror("Error", "Authentication failed. User not found.")
        except Error as e:
            messagebox.showerror("Error", f"Login failed: {e}")

    def show_passwords(self, user_id):
        # Implement the logic to display and manage passwords here
        pass

if __name__ == "__main__":
    root = tk.Tk()
    app = PasswordManagerApp(root)
    root.mainloop()

legacy/CryptwizWithGui.py
Raqeeb27/CryptWizard
## Import Modules
import os
from cryptography.fernet import Fernet

##------------------------------------------------------------------------
# Key Generation Function

def generate_key():
    try:
        key = Fernet.generate_key()    
        with open(key_file,'wb') as file :
            file.write(key)
    except:
        print("\nError in generating the Key file !!!\n")
        exit()

##------------------------------------------------------------------------
# Key Load Function

def load_key():
    try:
        with open(key_file, 'rb') as file:
            key = file.read()
        return key
    except:
        print("\nError in Loading the Key !!!\n")
        exit()

##------------------------------------------------------------------------
# Create Account Function

def create_acc():
    # Username with no leading and trailing white spaces
    user_name = input("\nUsername : ").title().strip()

    # Checking username characters length
    if user_name == '' :
        print('Username required !!!')
        return
        
    elif len(user_name) < 3 or len(user_name) > 15 :
        print("Only 3 - 15 characters allowed in Username")
        return
    
    else:
        # Padding with " ", if length < 15
        while len(user_name) < 15:
            user_name = user_name + " "

    user_pwd = input("Password : ")    

    if user_pwd == '':
        print('User Password required !!!')

    elif user_pwd.count(" ") != 0:
        print("\nPassword can't have space!!!")

    elif len(user_pwd) < 4 or len(user_pwd) > 12:
        print("\nPassword must have 4 - 12 characters !!!")
    
    else:
        try:
            with open(passwords_file, 'a') as file:
                # Encrypt and store password
                encrypt_pwd = master_key.encrypt(user_pwd.encode()).decode()
                file.write(f"\n {user_name}  |  {encrypt_pwd}" )
            print("\nUsername with Password saved Successfully.")
        except:
            print("\nError in Writing to 'passwords.txt' file !!!\n")
            exit()

##------------------------------------------------------------------------
# View Data Function

def view_data():
    line_number = 1
    try:
        with open(passwords_file, 'r') as file:
            lines = file.readlines()
            # Checking data
            if len(lines) < 3:
                print("\nNo Data !!!")
                return
            
            # Structred Display
            print("\n----------------------------------------------")
            print("|S.No.|      Username      |     Password    |\n----------------------------------------------")

            for line in lines:
                # Ignoring first 2 lines of file
                if line_number < 3:
                    line_number += 1
                    continue

                data = line.rstrip()
                user_name, user_pwd = data.split("  |  ")
                # Decrypt and read password
                decrypt_pwd = master_key.decrypt(user_pwd.encode()).decode()

                # Padding with " ", if length < 12
                while len(decrypt_pwd) < 12:
                    decrypt_pwd = decrypt_pwd + " "

                if line_number < 12:
                    print(f"| {line_number - 2}.  |  {user_name}  |   {decrypt_pwd}  |")
                else:
                    print(f"| {line_number - 2}. |  {user_name}  |   {decrypt_pwd}  |")

                line_number += 1
            print("----------------------------------------------")
    except:
        print("\nError in Reading from 'passwords.txt' file !!!\n")
        exit()

##------------------------------------------------------------------------
# Access Control

master_pwd = input("\n----- PASSWORD MANAGER -----\n\nMaster Password : ")

if master_pwd != '2023':
    print("\nACCESS DECLINED !!!\nIncorrect Master Password.\n")
    exit()

print("\nACCESS GRANTED !!!\nWelcome\n")

##------------------------------------------------------------------------
## Setting up Password_Manager_Files directory

workingDirectory = os.getcwd()
manager_dir = 'Password_Manager_Files'
path = os.path.join(workingDirectory, manager_dir)

##------------------------------------------------------------------------
# Creating output directory

try:
    if not os.path.exists(path):
        os.makedirs(path)
except:
    print(f"\nError in Creating directory\n")
    exit()

##------------------------------------------------------------------------
# Files

passwords_file = 'Password_Manager_Files/passwords.txt'
key_file = 'Password_Manager_Files/key_file.key'

##------------------------------------------------------------------------
# Initializing password.txt file

if (not os.path.exists(passwords_file)) or os.path.getsize(passwords_file) == 0:
    try:
        with open(passwords_file, 'a') as file:
            file.write("     Username     |     Password    \n------------------------------------------------------------------------------------" )
    except:
        print("\nError in Creating passwords.txt file !!!\n")
        exit()
    
##------------------------------------------------------------------------
# Generate Key_file

if not os.path.exists(key_file):
    generate_key()

##------------------------------------------------------------------------
# Setting up the KEY

key = load_key() + master_pwd.encode()
master_key = Fernet(key)

##------------------------------------------------------------------------
# Menu Driven Display

while True:

    mode = input("\n----- PASSWORD MANAGER -----\n\n1. CREATE Account\n2. VIEW Data\n3. Quit\n\n -->  ")

    if mode == '1':
        create_acc()
        input("\nPress Enter to Continue....")

    elif mode == '2':
        view_data()
        input("\n\nPress Enter to continue....")

    elif mode == '3':
        print("\nThank You !!!\n")
        break

    else:
        input("\nInvalid Input\nPress Enter to continue....")

legacy/app1.py
Raqeeb27/CryptWizard
## Import Modules
import os
import mysql.connector
from mysql.connector import Error
from cryptography.fernet import Fernet
import getpass
from time import sleep
import bcrypt
import base64

##------------------------------------------------------------------------
# Function to establish a database connection

db_config = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': 'asdf'
}

def connect_to_database():
    try:
        connection = mysql.connector.connect(**db_config)
        if connection.is_connected():
            return connection
    except Error as e:
        print("\nError connecting to the database:", e)
    return None

##------------------------------------------------------------------------
# Function to initialize database

def initialize_database():
    connection = connect_to_database()
    if connection:
        try:
            cursor = connection.cursor()
            
            # Create the database if it doesn't exist
            cursor.execute("CREATE DATABASE IF NOT EXISTS passwordmanager")
            cursor.execute("USE passwordmanager")

            # Create the Users table if it doesn't exist
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS Users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(255) NOT NULL,
                    salt CHAR(29) NOT NULL,
                    master_key VARCHAR(255) NOT NULL
                )
            """)

            # Create the Passwords table if it doesn't exist
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS Passwords (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT,
                    website VARCHAR(255) NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    FOREIGN KEY (user_id) REFERENCES Users(id)
                )
            """)

            connection.commit()
            db_config['database'] = 'passwordmanager'

        except Error as e:
            print("Error initializing database:", e)
        finally:
            cursor.close()
            connection.close()

##------------------------------------------------------------------------
# Initialize cipher key using user's master key

def initialize_cipher_key(master_key,salt):
    # Derive the key from the master password and salt using a key derivation function (KDF)
    '''kdf_key = bcrypt.kdf(
        password=master_key,
        salt=salt,
        desired_key_bytes=32,  # Fernet key length is 32 bytes
        rounds=100000,  # You can adjust the number of rounds for your security needs
        #algorithm="sha256"
    )
    return Fernet(base64.urlsafe_b64encode(kdf_key))'''
##------------------------------------------------------------------------
# Function to store password for a user to the database

def record_password(user_id, website, password):
    # Encrypt the password using cipher key
    #encrypted_password = cipher_key.encrypt(password)
    #print(type(encrypted_password))
    connection = connect_to_database()
    if connection:
        try:
            cursor = connection.cursor()
            query = "INSERT INTO Passwords (user_id, website, password) VALUES (%s, %s, %s)"
            cursor.execute(query, (user_id, website, password))
            connection.commit()
            print(f"\nPassword for '{website}' saved successfully!")
            input("\nPress Enter to Continue....")

        except Error as e:
            print("Error adding password:", e)
        finally:
            cursor.close()
            connection.close()
    
##------------------------------------------------------------------------
# Function to retrieve password for a user from the database

def lookup_password(user_id, username, website):
    connection = connect_to_database()
    if connection:
        try:
            cursor = connection.cursor()
            query = "SELECT password FROM Passwords WHERE user_id = %s AND website = %s"
            cursor.execute(query, (user_id, website))
            result = cursor.fetchone()
            if result:
                password = result[0]
                # Decrypt the password
                #decrypted_password = cipher_key.decrypt(encrypted_password.encode()).decode()
                print(f"\nUsername: {username}")
                print(f"Password for '{website}' : {password}")
            else:
                print(f"\nNo password found for '{website}'")
            input("\nPress Enter to Continue....")

        except Error as e:
            print("Error retrieving password:", e)
        finally:
            cursor.close()
            connection.close()

##------------------------------------------------------------------------
# Function to check unername and password format

def is_valid(cred_type,visible = True):

    if cred_type == ("Username") :
        credential = input("\nEnter Username : ").title().strip()
        # Checking username length
        if credential == '' :
            print('Username required !!!')
            return None
        elif len(credential) < 3 or len(credential) > 25 :
            print("Only 3 - 25 characters allowed in Username")
            return None
        else:
            return credential
        
    elif cred_type == ("Password"):
        if visible:
            credential = input("Enter Password : ")
        else:
            credential = getpass.getpass("Enter Password : ")
        # Checking password length
        if credential == '':
            print('User Password required !!!')
            return None
        elif credential.count(" ") != 0:
            print("\nPassword can't have space!!!")
            return None
        elif len(credential) < 4 or len(credential) > 25:
            print("\nPassword must have 4 - 25 characters !!!")
            return None
        else:
            return credential

    elif cred_type == ("Website") :
        credential = input("\nEnter Website : ").strip()
        # Checking website length
        if credential == '' :
            print('Website required !!!')
            return None
        else:
            return credential
        
##------------------------------------------------------------------------
# Function to create Hash of User Master key

def hash_master_key(master_password, salt):
    return bcrypt.hashpw(master_password.encode(), salt)

##------------------------------------------------------------------------
# Create User Function

def register_user():
    print("\n------ CREATE USER ACCOUNT ------")
    cred_check = is_valid("Username")
    if cred_check:
        username = cred_check
    else:
        return
    cred_check = is_valid("Password")
    if cred_check:
        master_password = cred_check
    else:
        return 
    confirm_password = input("Confirm Password: ")
    if confirm_password == master_password :        
        # Generate a random salt
        salt = bcrypt.gensalt()        
        # Derive the master key using the master password and salt
        hashed_master_key = hash_master_key(master_password, salt)
        connection = connect_to_database()
        if connection:
            try:
                cursor = connection.cursor()
                query = "INSERT INTO Users (username, salt, master_key) VALUES (%s, %s, %s)"
                cursor.execute(query, (username, salt.decode(), hashed_master_key.decode()))
                connection.commit()
                print("\nUser created successfully!")
            except Error as e:
                print(f"Error creating User Account: {e}\n")
            finally:
                cursor.close()
                connection.close()
    else:
        print("\nPassword didn't match,\nUser account creation failed!")

##------------------------------------------------------------------------
# User Login Function 

def user_login():
    print("\n------ USER LOGIN ------")
    cred_check = is_valid("Username")
    if cred_check:
        username = cred_check
    else:
        return None,None,None
    cred_check = is_valid("Password",False)
    if cred_check:
        input_password = cred_check
    else:
        return None,None,None
    connection = connect_to_database()
    if connection:
        try:
            cursor = connection.cursor()
            query1 = "SELECT id, username, salt, master_key FROM Users WHERE username = %s"
            cursor.execute(query1, (username, ))
            result = cursor.fetchone()
            if result:
                logged_user_id, logged_username, stored_salt, stored_master_key = result
                # Derive the master key using the provided master password and stored salt
                user_master_key = hash_master_key(input_password, stored_salt.encode())

                if user_master_key == stored_master_key.encode():
                    print("\nAuthentication successful !!!\n")
                    # Generate a salt for the Fernet key
                    salt = os.urandom(16)

                    # Generate a Fernet key from the user's master key and the salt
                    cipher_key = initialize_cipher_key(input_password, salt)
                    # Initializing cipher key with user master key
                    #cipher_key = initialize_cipher_key(user_master_key)
                    #print(type(cipher_key))

                    sleep(1)
                    return logged_user_id,logged_username,cipher_key
                else:
                    print("\nAuthentication failed !!!\nUsername or Password is Incorrect\n")
            else:
                print("\n Unrecognized User - Authentication failed !!!")
            sleep(0.7)
            return None,None,None
            
        except Error as e:
            print("Error in User Login: ", e)
        finally:
            cursor.close()
            connection.close()

##------------------------------------------------------------------------
# Menu Drien Logged in User display

def logged_user_display():
    while True:
        print(f"\n--------\n| User | --> {logged_username}\n--------\n")
        print("1. New Password Record")
        print("2. Retrieve password")
        print("3. Logout\n")

        user_choice = input(" -->  ")

        if user_choice == '1':
            cred_check = is_valid("Website")
            if cred_check:
                website = cred_check
            else:
                return
            
            cred_check = is_valid("Password")
            if cred_check:
                password = cred_check
            else:
                return
            confirm_password = input("Confirm Password: ")
            if confirm_password == password :
                record_password(logged_user_id,website, password)
            else:
                print("\nPassword didn't match\nFailed to save Website and Password!")

        elif user_choice == '2':
            cred_check = is_valid("Website")
            if cred_check:
                website = cred_check
            else:
                return
            lookup_password(logged_user_id,logged_username,website)

        elif user_choice == '3':
            print("\nLogout Successfull !!!")
            sleep(1)
            break
        else:
            print("\nInvalid choice. Please try again.")
            sleep(0.7)
##------------------------------------------------------------------------
# Menu Drien main display

initialize_database()

while True:

    print("\n----------------------------------\n  --------- CryptWizard --------\n   ----- PASSWORD MANAGER -----\n")
    choice = input("1. Register\n2. Login\n3. Exit\n\n -->  ")
    if choice == '1':
        register_user()
        input("\nPress Enter to Continue....")        
    elif choice == '2':
        logged_user_id, logged_username, cipher_key = user_login()
        if logged_user_id:
            logged_user_display()
            input("\nPress Enter to Continue....")
        else:
            input("\nPress Enter to Continue....")
    elif choice == '3':
        print("\n!!! Thank You !!!\n")
        sleep(0.6)
        print('\n ---------- CryptWizard -----------\n\n Your security is our top priority.\n\t Have a great day!\n\n')
        break
    else:
        print("Invalid choice. Please try again.")
        sleep(0.7)
legacy/app2.py
Raqeeb27/CryptWizard
import sys
import bcrypt
import mysql.connector
from mysql.connector import Error
from PyQt5.QtCore import Qt 
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QDialog, QLineEdit, QMessageBox, QHBoxLayout

app = QApplication(sys.argv)

class LoggedinDialog(QDialog):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("Login")
        self.setGeometry(400, 180, 500, 450)
        self.register_window = RegistrationDialog()

        self.initUI()

    def initUI(self):

        layout = QVBoxLayout()
        horizontal_layout = QHBoxLayout()

        layout.addSpacing(10)

        self.dashboard_label = QLabel("PASSWORD MANAGER DASHBOARD", self)
        self.dashboard_label.setAlignment(Qt.AlignHCenter)
        layout.addWidget(self.dashboard_label)

        layout.addSpacing(15)

        self.welcome_label = QLabel("Welcome, {User's Name}!", self)
        self.welcome_label.setAlignment(Qt.AlignLeft)  
        horizontal_layout.addWidget(self.welcome_label)

        self.secritylevel_label = QLabel("Security Level: High  ", self)
        self.secritylevel_label.setAlignment(Qt.AlignRight)  
        horizontal_layout.addWidget(self.secritylevel_label)

        layout.addLayout(horizontal_layout)
        layout.addSpacing(20)

        self.summary_label = QLabel("Dashboard Summary:", self)
        self.summary_label.setAlignment(Qt.AlignLeft)  
        layout.addWidget(self.summary_label)

        layout.addSpacing(1)

        self.total_pwds_label = QLabel("- Total Passwords: { X}", self)
        self.total_pwds_label.setAlignment(Qt.AlignLeft)  
        layout.addWidget(self.total_pwds_label)
        layout.addSpacing(1)

        self.recent_act_label = QLabel("- Recent Activity: { Z}", self)
        self.recent_act_label.setAlignment(Qt.AlignLeft)  
        layout.addWidget(self.recent_act_label)

        layout.addSpacing(20)

        self.pwd_vault_label = QLabel("Password Vault:", self)
        self.pwd_vault_label.setAlignment(Qt.AlignLeft)  
        layout.addWidget(self.pwd_vault_label)

        layout.addStretch()

        self.setLayout(layout)

# -----------------------------------------------------------------------------------------

class LoginDialog(QDialog):

    def __init__(self):
        super().__init__()

        self.setWindowTitle("Login")
        self.setGeometry(500, 280, 300, 250)
        self.register_window = RegistrationDialog()

        self.initUI()

    def initUI(self):

        layout = QVBoxLayout()

        self.username_label = QLabel("Username", self)
        self.username_input = QLineEdit(self)
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_input)

        self.pwd_label = QLabel("Password", self)
        self.password_input = QLineEdit(self)
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.pwd_label)
        layout.addWidget(self.password_input)


        self.email_label = QLabel("Email", self)
        self.email_input = QLineEdit(self)
        layout.addWidget(self.email_label)
        layout.addWidget(self.email_input)

        self.login_button = QPushButton("Login", self)
        layout.addWidget(self.login_button)

        self.setLayout(layout)

        self.login_button.clicked.connect(self.loginAction)

    def loginAction(self):

        username = self.username_input.text()
        password = self.password_input.text()
        email = self.email_input.text()

        if not username or not password or not email:
            QMessageBox.warning(self, "Login Error", "Please fill in all fields.")
        else:
            connection = self.register_window.main_window.connect_to_database()
            if connection:
                try:
                    cursor = connection.cursor()
                    query1 = "SELECT id, username, salt, master_key FROM Users WHERE username = %s"
                    cursor.execute(query1, (username, ))
                    result = cursor.fetchone()
                    if result:
                        logged_user_id, logged_username, stored_salt, stored_master_key = result
                        # Derive the master key using the provided master password and stored salt
                        user_master_key = self.register_window.hash_master_key(password, stored_salt.encode())

                        if user_master_key == stored_master_key.encode():
                            QMessageBox.information(self, "Login Successful", "Login was successful!")
                            self.accept()
                            loggedin_dialog = LoggedinDialog()
                            loggedin_dialog.exec_()
                            # Close the registration dialog
                            #self.accept()
                            # Generate a salt for the Fernet key
                            #salt = os.urandom(16)

                            # Generate a Fernet key from the user's master key and the salt
                            #cipher_key = initialize_cipher_key(input_password, salt)
                            # Initializing cipher key with user master key
                            #cipher_key = initialize_cipher_key(user_master_key)
                            #print(type(cipher_key))

                        else:
                            QMessageBox.warning(self, "Login Error", "Authentication failed, Username or Password is Incorrect !!!")
                    else:
                        QMessageBox.warning(self, "Login Error", "Unrecognized User - Authentication failed !!!")
                    
                    
                except Error as e:
                    QMessageBox.warning(self, "Login Error", "Error in User Login")
                finally:
                    cursor.close()
                    connection.close()

# -----------------------------------------------------------------------------------------

class RegistrationDialog(QDialog):

    def __init__(self):
        super().__init__()

        self.setWindowTitle("Registration")
        self.setGeometry(500, 280, 300, 250)
        self.main_window = MyWindow()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        self.username_label = QLabel("Username", self)
        self.username_input = QLineEdit(self)
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_input)

        self.pwd_label = QLabel("Password", self)
        self.password_input = QLineEdit(self)
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.pwd_label)
        layout.addWidget(self.password_input)

        self.confirm_pwd_label = QLabel("Confirm Password", self)
        self.confirm_pwd_input = QLineEdit(self)
        self.confirm_pwd_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.confirm_pwd_label)
        layout.addWidget(self.confirm_pwd_input)

        self.email_label = QLabel("Email", self)
        self.email_input = QLineEdit(self)
        layout.addWidget(self.email_label)
        layout.addWidget(self.email_input)

        self.register_button = QPushButton("Register", self)
        layout.addWidget(self.register_button)

        self.setLayout(layout)

        self.register_button.clicked.connect(self.registrationAction)


    def registrationAction(self):

        username = self.username_input.text()
        password = self.password_input.text()
        confirm_pwd = self.confirm_pwd_input.text()
        email = self.email_input.text()

        if not username or not password or not email:
            QMessageBox.warning(self, "Registration Error", "Please fill in all fields.")

        elif password != confirm_pwd:
            QMessageBox.warning(self, "Registration Error", "Input Passwords correctly !")
        
        else:

            salt = bcrypt.gensalt()        

            hashed_master_key = self.hash_master_key(password, salt)
            
            connection = self.main_window.connect_to_database()
            if connection:
                try:
                    cursor = connection.cursor()
                    query = "INSERT INTO Users (username, email, salt, master_key) VALUES (%s, %s, %s, %s)"
                    cursor.execute(query, (username, email, salt.decode(), hashed_master_key.decode()))
                    connection.commit()
                    # Show a message box indicating successful registration
                    QMessageBox.information(self, "Registration Successful", "Registration was successful!")

                    # Close the registration dialog
                    self.accept()
                except Error as e:
                    QMessageBox.warning(self, "Registration Error", "Error in User Registration")
                finally:
                    cursor.close()
                    connection.close()


    def hash_master_key(self,master_password, salt):
        return bcrypt.hashpw(master_password.encode(), salt)

# -----------------------------------------------------------------------------------------

class MyWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        
        self.db_config = {
            'host': '127.0.0.1',
            'user': 'root',
            'password': 'asdf'
        }
        self.setWindowTitle("CryptWizard - Password Manager")
        self.setGeometry(450, 250, 400, 300)

        self.initUI()


    def connect_to_database(self):
        try:
            connection = mysql.connector.connect(**self.db_config)
            if connection.is_connected():
                return connection
        except Error as e:
            QMessageBox.warning(self, "Connection Error", "Can't connect to Database")


    def initialize_database(self):
        connection = self.connect_to_database()
        if connection:
            try:                
                cursor = connection.cursor()
                
                # Create the database if it doesn't exist
                cursor.execute("CREATE DATABASE IF NOT EXISTS passwordmanager")
                cursor.execute("USE passwordmanager")

                # Create the Users table if it doesn't exist
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS Users (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        username VARCHAR(255) NOT NULL,
                        email VARCHAR(20) NOT NULL,
                        salt CHAR(29) NOT NULL,
                        master_key VARCHAR(255) NOT NULL
                    )
                """)

                # Create the Passwords table if it doesn't exist
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS Passwords (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT,
                        website VARCHAR(255) NOT NULL,
                        password VARCHAR(255) NOT NULL,
                        FOREIGN KEY (user_id) REFERENCES Users(id)
                    )
                """)

                connection.commit()
                self.db_config['database'] = 'passwordmanager'

            except Error as e:
                QMessageBox.warning(self, "Connection Error", "Can't connect to Database")
            finally:
                cursor.close()
                connection.close()

    def initUI(self):
        self.initialize_database()
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout()

        layout.addSpacing(10)

        self.pwd_manager_label = QLabel("PASSWORD MANAGER", self)
        layout.addWidget(self.pwd_manager_label)

        layout.addSpacing(20)  # Increase spacing between label and buttons

        self.register_button = QPushButton("Register", self)
        self.register_button.setFixedSize(80, 30)
        layout.addWidget(self.register_button)

        self.login_button = QPushButton("Login", self)
        self.login_button.setFixedSize(80, 30)
        layout.addWidget(self.login_button)

        self.exit_button = QPushButton("Exit", self)
        self.exit_button.setFixedSize(80, 30)
        layout.addWidget(self.exit_button)

        layout.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        layout.setSpacing(10)  # Set spacing between widgets to 10 pixels

        layout.addStretch()

        self.register_button.clicked.connect(self.showRegistrationDialog)
        self.login_button.clicked.connect(self.showloginDialog)
        self.exit_button.clicked.connect(self.closeApplication)

        central_widget.setLayout(layout)

    def showRegistrationDialog(self):
        registration_dialog = RegistrationDialog()
        registration_dialog.exec_()

    def showloginDialog(self):
        login_dialog = LoginDialog()
        login_dialog.exec_()

    def closeApplication(self):
        self.close()


window = MyWindow()
window.show()

sys.exit(app.exec_())

legacy/app3.py
Raqeeb27/CryptWizard
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'RegisterDialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_RegisterDialog(object):
    def setupUi(self, RegisterDialog):
        RegisterDialog.setObjectName("RegisterDialog")
        RegisterDialog.resize(513, 416)
        self.acc_register_label = QtWidgets.QLabel(RegisterDialog)
        self.acc_register_label.setGeometry(QtCore.QRect(130, 20, 281, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(22)
        font.setBold(False)
        font.setUnderline(True)
        font.setWeight(50)
        self.acc_register_label.setFont(font)
        self.acc_register_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.acc_register_label.setObjectName("acc_register_label")
        self.username_label = QtWidgets.QLabel(RegisterDialog)
        self.username_label.setGeometry(QtCore.QRect(50, 70, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(13)
        self.username_label.setFont(font)
        self.username_label.setObjectName("username_label")
        self.username_input_field = QtWidgets.QLineEdit(RegisterDialog)
        self.username_input_field.setGeometry(QtCore.QRect(40, 100, 391, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(13)
        self.username_input_field.setFont(font)
        self.username_input_field.setText("")
        self.username_input_field.setObjectName("username_input_field")
        self.password_label = QtWidgets.QLabel(RegisterDialog)
        self.password_label.setGeometry(QtCore.QRect(50, 140, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(13)
        self.password_label.setFont(font)
        self.password_label.setObjectName("password_label")
        self.pwd_input_field = QtWidgets.QLineEdit(RegisterDialog)
        self.pwd_input_field.setGeometry(QtCore.QRect(40, 170, 391, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(13)
        self.pwd_input_field.setFont(font)
        self.pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Password)
        self.pwd_input_field.setObjectName("pwd_input_field")
        self.confirm_pwd_label = QtWidgets.QLabel(RegisterDialog)
        self.confirm_pwd_label.setGeometry(QtCore.QRect(50, 210, 181, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(13)
        self.confirm_pwd_label.setFont(font)
        self.confirm_pwd_label.setObjectName("confirm_pwd_label")
        self.confirm_pwd_input_field = QtWidgets.QLineEdit(RegisterDialog)
        self.confirm_pwd_input_field.setGeometry(QtCore.QRect(40, 240, 391, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(13)
        self.confirm_pwd_input_field.setFont(font)
        self.confirm_pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Password)
        self.confirm_pwd_input_field.setObjectName("confirm_pwd_input_field")
        self.register_button = QtWidgets.QPushButton(RegisterDialog)
        self.register_button.setGeometry(QtCore.QRect(80, 320, 141, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.register_button.setFont(font)
        self.register_button.setObjectName("register_button")
        self.cancel_button = QtWidgets.QPushButton(RegisterDialog)
        self.cancel_button.setGeometry(QtCore.QRect(290, 320, 141, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.cancel_button.setFont(font)
        self.cancel_button.setObjectName("cancel_button")
        self.username_error_label = QtWidgets.QLabel(RegisterDialog)
        self.username_error_label.setGeometry(QtCore.QRect(160, 70, 341, 31))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.username_error_label.setFont(font)
        self.username_error_label.setStyleSheet("color: red;")
        self.username_error_label.setObjectName("username_error_label")
        self.username_error_label.hide()
        self.password_error_label = QtWidgets.QLabel(RegisterDialog)
        self.password_error_label.setGeometry(QtCore.QRect(160, 140, 341, 31))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.password_error_label.setFont(font)
        self.password_error_label.setStyleSheet("color: red;")
        self.password_error_label.setObjectName("password_error_label")
        self.password_error_label.hide()
        self.confirm_pwd_error_label = QtWidgets.QLabel(RegisterDialog)
        self.confirm_pwd_error_label.setGeometry(QtCore.QRect(220, 210, 281, 31))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.confirm_pwd_error_label.setFont(font)
        self.confirm_pwd_error_label.setStyleSheet("color: red;")
        self.confirm_pwd_error_label.setObjectName("confirm_pwd_error_label")
        self.confirm_pwd_error_label.hide()
        self.pwd_visible_checkbox = QtWidgets.QCheckBox(RegisterDialog)
        self.pwd_visible_checkbox.setGeometry(QtCore.QRect(410, 180, 16, 17))
        self.pwd_visible_checkbox.setObjectName("pwd_visible_checkbox")
        self.confirm_pwd_visible_checkbox = QtWidgets.QCheckBox(RegisterDialog)
        self.confirm_pwd_visible_checkbox.setGeometry(QtCore.QRect(410, 250, 16, 17))
        self.confirm_pwd_visible_checkbox.setObjectName("confirm_pwd_visible_checkbox")

        self.retranslateUi(RegisterDialog)
        QtCore.QMetaObject.connectSlotsByName(RegisterDialog)

    def retranslateUi(self, RegisterDialog):
        _translate = QtCore.QCoreApplication.translate
        RegisterDialog.setWindowTitle(_translate("RegisterDialog", "Registration"))
        self.acc_register_label.setText(_translate("RegisterDialog", "Account Registration"))
        self.username_label.setText(_translate("RegisterDialog", "Username"))
        self.password_label.setText(_translate("RegisterDialog", "Password"))
        self.confirm_pwd_label.setText(_translate("RegisterDialog", "Confirm Password"))
        self.register_button.setText(_translate("RegisterDialog", "Register"))
        self.cancel_button.setText(_translate("RegisterDialog", "Cancel"))
        self.username_error_label.setText(_translate("RegisterDialog", "*username_error_label"))
        self.password_error_label.setText(_translate("RegisterDialog", "*password_error_label"))
        self.confirm_pwd_error_label.setText(_translate("RegisterDialog", "*confirm_pwd_error_label"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    RegisterDialog = QtWidgets.QDialog()
    ui = Ui_RegisterDialog()
    ui.setupUi(RegisterDialog)

        # Create an instance of your QDialog
    dialog = RegisterDialog

    # Connect the exit_button click event to close the dialog
    ui.cancel_button.clicked.connect(dialog.close)

    RegisterDialog.show()
    sys.exit(app.exec_())

scripts/RegisterDialog.py
Raqeeb27/CryptWizard
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'SigninDialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_SigninDialog(object):
    def setupUi(self, SigninDialog):
        SigninDialog.setObjectName("SigninDialog")
        SigninDialog.resize(513, 417)
        self.sign_in_label = QtWidgets.QLabel(SigninDialog)
        self.sign_in_label.setGeometry(QtCore.QRect(200, 30, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(22)
        font.setBold(False)
        font.setUnderline(True)
        font.setWeight(50)
        self.sign_in_label.setFont(font)
        self.sign_in_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.sign_in_label.setObjectName("sign_in_label")
        self.username_label = QtWidgets.QLabel(SigninDialog)
        self.username_label.setGeometry(QtCore.QRect(70, 90, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(12)
        self.username_label.setFont(font)
        self.username_label.setObjectName("username_label")
        self.password_label = QtWidgets.QLabel(SigninDialog)
        self.password_label.setGeometry(QtCore.QRect(70, 160, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(12)
        self.password_label.setFont(font)
        self.password_label.setObjectName("password_label")
        self.forgot_pwd_button = QtWidgets.QPushButton(SigninDialog)
        self.forgot_pwd_button.setGeometry(QtCore.QRect(60, 240, 91, 21))
        font = QtGui.QFont()
        font.setFamily("Corbel")
        font.setPointSize(9)
        font.setUnderline(True)
        self.forgot_pwd_button.setFont(font)
        self.forgot_pwd_button.setStyleSheet("color : blue;")
        self.forgot_pwd_button.setFlat(True)
        self.forgot_pwd_button.setObjectName("forgot_pwd_button")
        self.confirm_button = QtWidgets.QPushButton(SigninDialog)
        self.confirm_button.setGeometry(QtCore.QRect(80, 300, 141, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.confirm_button.setFont(font)
        self.confirm_button.setObjectName("confirm_button")
        self.cancel_button = QtWidgets.QPushButton(SigninDialog)
        self.cancel_button.setGeometry(QtCore.QRect(290, 300, 141, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.cancel_button.setFont(font)
        self.cancel_button.setObjectName("cancel_button")
        self.username_input_field = QtWidgets.QLineEdit(SigninDialog)
        self.username_input_field.setGeometry(QtCore.QRect(60, 120, 391, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(13)
        self.username_input_field.setFont(font)
        self.username_input_field.setObjectName("username_input_field")
        self.pwd_input_field = QtWidgets.QLineEdit(SigninDialog)
        self.pwd_input_field.setGeometry(QtCore.QRect(60, 190, 391, 31))
        font = QtGui.QFont()
        font.setFamily("Bodoni MT")
        font.setPointSize(13)
        self.pwd_input_field.setFont(font)
        self.pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Password)
        self.pwd_input_field.setObjectName("pwd_input_field")
        self.username_error_label = QtWidgets.QLabel(SigninDialog)
        self.username_error_label.setGeometry(QtCore.QRect(180, 90, 331, 31))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.username_error_label.setFont(font)
        self.username_error_label.setStyleSheet("color: red;")
        self.username_error_label.setObjectName("username_error_label")

        self.username_error_label.hide() 

        self.password_error_label = QtWidgets.QLabel(SigninDialog)
        self.password_error_label.setGeometry(QtCore.QRect(180, 160, 301, 31))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.password_error_label.setFont(font)
        self.password_error_label.setStyleSheet("color: red;")
        self.password_error_label.setObjectName("password_error_label")
        self.password_error_label.hide()

        self.retranslateUi(SigninDialog)
        QtCore.QMetaObject.connectSlotsByName(SigninDialog)

    def retranslateUi(self, SigninDialog):
        _translate = QtCore.QCoreApplication.translate
        SigninDialog.setWindowTitle(_translate("SigninDialog", "SigninDialog"))
        self.sign_in_label.setText(_translate("SigninDialog", "Sign in"))
        self.username_label.setText(_translate("SigninDialog", "Username"))
        self.password_label.setText(_translate("SigninDialog", "Password"))
        self.forgot_pwd_button.setText(_translate("SigninDialog", "Forgot Password"))
        self.confirm_button.setText(_translate("SigninDialog", "Confirm"))
        self.cancel_button.setText(_translate("SigninDialog", "Cancel"))
        self.username_error_label.setText(_translate("SigninDialog", "*username_error_label"))
        self.password_error_label.setText(_translate("SigninDialog", "*password_error_label"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    SigninDialog = QtWidgets.QDialog()
    ui = Ui_SigninDialog()
    ui.setupUi(SigninDialog)

    # Create an instance of your QDialog
    dialog = SigninDialog

    # Connect the exit_button click event to close the dialog
    ui.cancel_button.clicked.connect(dialog.close)

    SigninDialog.show()
    sys.exit(app.exec_())

scripts/SigninDialog.py
Raqeeb27/CryptWizard
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QLineEdit, QPushButton
import pyDes
import hashlib

def encrypt_with_des(master_password, app_password):
    # Ensure the master password is 8 bytes long (or pad it if it's shorter)
    master_password = master_password.ljust(8, '\0')[:8]

    # Convert the master password to bytes
    master_password_bytes = master_password.encode('utf-8')

    # Create a DES object with the master password as the key
    des = pyDes.des(master_password_bytes, pyDes.ECB, pad=None, padmode=pyDes.PAD_PKCS5)

    # Convert the application password to bytes
    app_password_bytes = app_password.encode('utf-8')

    # Encrypt the application password
    encrypted_password = des.encrypt(app_password_bytes)

    # Convert the encrypted password bytes to a hexadecimal representation
    encrypted_password_hex = encrypted_password.hex()

    print(encrypted_password,encrypted_password_hex)
    return encrypted_password_hex


# Import the encrypt_with_des function here...

class PasswordManagerApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Password Manager")

        main_widget = QWidget()
        main_layout = QVBoxLayout()

        # Create QLabel and QLineEdit for the master password
        master_password_label = QLabel("Master Password:")
        self.master_password_input = QLineEdit()
        main_layout.addWidget(master_password_label)
        main_layout.addWidget(self.master_password_input)

        # Create QLabel and QLineEdit for the application password
        app_password_label = QLabel("Application Password:")
        self.app_password_input = QLineEdit()
        main_layout.addWidget(app_password_label)
        main_layout.addWidget(self.app_password_input)

        # Create a QPushButton to perform the encryption
        encrypt_button = QPushButton("Encrypt")
        encrypt_button.clicked.connect(self.encrypt_password)
        main_layout.addWidget(encrypt_button)

        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

    def encrypt_password(self):
        master_password = self.master_password_input.text()
        app_password = self.app_password_input.text()

        if master_password and app_password:
            encrypted_password = encrypt_with_des(master_password, app_password)
            # You can now do something with the encrypted password, e.g., store it in your database or display it.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = PasswordManagerApp()
    window.show()
    sys.exit(app.exec_())


scripts/encrypt.py
Raqeeb27/CryptWizard
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'qt_main.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QMessageBox
from PyQt5.QtCore import QTimer
import bcrypt

# Import the Ui_RegisterDialog class from registerdialog.py
from RegisterDialog import Ui_RegisterDialog
from SigninDialog import Ui_SigninDialog

import mysql.connector
from mysql.connector import Error


class Ui_MainWindow(object):
    def __init__(self):
        self.msg_box = None 
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(599, 473)
        MainWindow.setSizeIncrement(QtCore.QSize(0, 0))
        font = QtGui.QFont()
        font.setPointSize(8)
        MainWindow.setFont(font)
        MainWindow.setAutoFillBackground(False)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pwd_manager_label = QtWidgets.QLabel(self.centralwidget)
        self.pwd_manager_label.setGeometry(QtCore.QRect(140, 100, 321, 51))
        self.pwd_manager_label.setSizeIncrement(QtCore.QSize(0, 0))
        font = QtGui.QFont()
        font.setFamily("Baskerville Old Face")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setKerning(True)
        self.pwd_manager_label.setFont(font)
        self.pwd_manager_label.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor))
        self.pwd_manager_label.setAutoFillBackground(False)
        self.pwd_manager_label.setTextFormat(QtCore.Qt.AutoText)
        self.pwd_manager_label.setScaledContents(False)
        self.pwd_manager_label.setObjectName("pwd_manager_label")
        self.register_button = QtWidgets.QPushButton(self.centralwidget)
        self.register_button.setGeometry(QtCore.QRect(200, 190, 201, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.register_button.setFont(font)
        self.register_button.setObjectName("register_button")

        # Connect the register_button click event to open the RegisterDialog
        self.register_button.clicked.connect(self.open_register_dialog)

        self.cryptwizard_label = QtWidgets.QLabel(self.centralwidget)
        self.cryptwizard_label.setGeometry(QtCore.QRect(190, 20, 241, 51))
        font = QtGui.QFont()
        font.setFamily("High Tower Text")
        font.setPointSize(30)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(True)
        font.setWeight(75)
        self.cryptwizard_label.setFont(font)
        self.cryptwizard_label.setObjectName("cryptwizard_label")
        self.sign_in_button = QtWidgets.QPushButton(self.centralwidget)
        self.sign_in_button.setGeometry(QtCore.QRect(200, 270, 201, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.sign_in_button.setFont(font)
        self.sign_in_button.setObjectName("sign_in_button")

        # Connect the register_button click event to open the RegisterDialog
        self.sign_in_button.clicked.connect(self.open_signin_dialog)

        self.exit_button = QtWidgets.QPushButton(self.centralwidget)
        self.exit_button.setGeometry(QtCore.QRect(200, 350, 201, 41))
        font = QtGui.QFont()
        font.setFamily("Bookman Old Style")
        font.setPointSize(12)
        self.exit_button.setFont(font)
        self.exit_button.setObjectName("exit_button")

        # Connect the exit_button click event to close the MainWindow
        self.exit_button.clicked.connect(MainWindow.close)

        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pwd_manager_label.setText(_translate("MainWindow", "  PASSWORD MANAGER"))
        self.register_button.setText(_translate("MainWindow", "Register"))
        self.cryptwizard_label.setText(_translate("MainWindow", "CryptWizard"))
        self.sign_in_button.setText(_translate("MainWindow", "Sign In"))
        self.exit_button.setText(_translate("MainWindow", "Exit"))

#--------------------------------------------------------------------------------------

    def open_register_dialog(self):
        register_dialog_obj.setupUi(register_dialog)
          
        # Connect the cancel_button click event to close the register_dialog
        register_dialog_obj.cancel_button.clicked.connect(self.cancel_register)
        register_dialog_obj.register_button.clicked.connect(self.register_user)
        self.exit_button.clicked.connect(register_dialog.close)        

        # Connect the checkbox state change to the toggle_echo_mode function
        register_dialog_obj.pwd_visible_checkbox.stateChanged.connect(self.pwd_checkbox_check)
        register_dialog_obj.confirm_pwd_visible_checkbox.stateChanged.connect(self.confirm_pwd_checkbox_check)

        # Show the RegisterDialog
        register_dialog.show()

    def open_signin_dialog(self):
        signin_dialog_obj.setupUi(signin_dialog)
        # Show the SigninDialog
        signin_dialog.show()
        # Connect the cancel_button click event to close the signin_dialog
        signin_dialog_obj.cancel_button.clicked.connect(self.cancel_signin)
        signin_dialog_obj.confirm_button.clicked.connect(self.signin_user)

        self.exit_button.clicked.connect(signin_dialog.close)


    def register_user(self):
        input_username = register_dialog_obj.username_input_field.text()
        input_password = register_dialog_obj.pwd_input_field.text()
        input_confirm_pwd = register_dialog_obj.confirm_pwd_input_field.text()

        cred_check, error_label = self.is_valid(input_username, "Username")
        username = ''
        if cred_check:
            register_dialog_obj.username_error_label.hide()
            username = cred_check
        elif error_label:
            register_dialog_obj.username_error_label.setText(error_label)
            register_dialog_obj.username_error_label.show()

        cred_check, error_label = self.is_valid(input_password, "Password")
        master_password = ''
        if cred_check:
            register_dialog_obj.password_error_label.hide()
            master_password = cred_check
        elif error_label:
            register_dialog_obj.password_error_label.setText(error_label)
            register_dialog_obj.password_error_label.show()

        cred_check, error_label = self.is_valid(input_confirm_pwd, "Confirm Password")
        confirm_password = ''
        if cred_check:
            register_dialog_obj.confirm_pwd_error_label.hide()
            confirm_password = cred_check
        elif error_label:
            register_dialog_obj.confirm_pwd_error_label.setText(error_label)
            register_dialog_obj.confirm_pwd_error_label.show()

        if len(username) >= 8 and len(master_password) >= 8 and len(confirm_password) != 0 :
            if confirm_password == master_password:
                # Generate a random salt
                salt = bcrypt.gensalt()        
                # Derive the master key using the master password and salt
                hashed_master_key = self.hash_master_key(master_password, salt)
                connection = self.connect_to_database()
                if connection:
                    try:
                        cursor = connection.cursor()
                        query = "INSERT INTO Users (username, salt, master_key) VALUES (%s, %s, %s)"
                        cursor.execute(query, (username, salt.decode(), hashed_master_key.decode()))
                        connection.commit()
                        self.show_message_box("Registration", "  Registration Successful  ", QMessageBox.Information)
                        register_dialog.close()
                    except Error as e:
                        self.show_message_box("Registration Error","Error in User Registration",QMessageBox.Critical)
                    finally:
                        cursor.close()
                        connection.close()
            else:
                self.show_message_box("Registration Error","Password didn't match\nRegistration failed!", QMessageBox.Critical)


    def signin_user(self):
        input_username = signin_dialog_obj.username_input_field.text()
        input_password = signin_dialog_obj.pwd_input_field.text()

        if input_username == '':
            signin_dialog_obj.username_error_label.setText("*Username required")
            signin_dialog_obj.username_error_label.show()
        else:
            signin_dialog_obj.username_error_label.hide()
        if input_password == '':
            signin_dialog_obj.password_error_label.setText("*User Password reqired")
            signin_dialog_obj.password_error_label.show()
        else:
            signin_dialog_obj.password_error_label.hide()

        if len(input_username) != 0 and len(input_password) != 0:
            connection = self.connect_to_database()
            if connection:
                try:
                    cursor = connection.cursor()
                    query1 = "SELECT id, username, salt, master_key FROM Users WHERE username = %s"
                    cursor.execute(query1, (input_username, ))
                    result = cursor.fetchone()
                    if result:
                        logged_user_id, logged_username, stored_salt, stored_master_key = result
                        # Derive the master key using the provided master password and stored salt
                        user_master_key = self.hash_master_key(input_password, stored_salt.encode())

                        if user_master_key == stored_master_key.encode():
                            
                            # Generate a salt for the Fernet key
                            #salt = os.urandom(16)

                            # Generate a Fernet key from the user's master key and the salt
                            #cipher_key = self.initialize_cipher_key(input_password, salt)
                            # Initializing cipher key with user master key
                            #cipher_key = initialize_cipher_key(user_master_key)

                            self.show_message_box("Login","Authentication successful !!!",QMessageBox.Information)
                            signin_dialog.close()
                            #return logged_user_id,logged_username,cipher_key
                        else:
                            self.show_message_box("Login Failed","Authentication failed !!!\nUsername or Password is Incorrect",QMessageBox.Critical)
                    else:
                        self.show_message_box("Login Failed", "Unrecognized User \n Authentication failed !!!", QMessageBox.Critical)
                    #sleep(0.7)
                    #return None,None,None
                    
                except Error as e:
                   self.show_message_box("Login Error","Error in User Login ", QMessageBox.Warning)
                finally:
                    cursor.close()
                    connection.close()

    def show_message_box(self, title, message, icon):
        self.msg_box = QMessageBox()
        self.msg_box.setWindowTitle(title)
        self.msg_box.setText(message)
        self.msg_box.setIcon(icon)
        self.msg_box.exec_()

    def cancel_register(self):
        register_dialog_obj.username_error_label.hide()
        register_dialog_obj.password_error_label.hide()
        register_dialog_obj.confirm_pwd_error_label.hide()
        register_dialog.close()
    def cancel_signin(self):
        signin_dialog_obj.username_error_label.hide()
        signin_dialog_obj.password_error_label.hide()
        signin_dialog.close()

    def pwd_checkbox_check(self, state):
        # Toggle the echo mode of pwd_input_field1 based on the state of show_password_checkbox1
        if state == QtCore.Qt.Checked:
            register_dialog_obj.pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Normal)
        else:
            register_dialog_obj.pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Password)
    def confirm_pwd_checkbox_check(self, state):
        # Toggle the echo mode of pwd_input_field2 based on the state of show_password_checkbox2
        if state == QtCore.Qt.Checked:
            register_dialog_obj.confirm_pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Normal)
        else:
            register_dialog_obj.confirm_pwd_input_field.setEchoMode(QtWidgets.QLineEdit.Password)
        

    def is_valid(self,credential,cred_type):
        credential = credential.strip()
        if cred_type == ("Username") :
            if credential == '' :
                error_message = "*Username Required"
            elif len(credential) < 8 :
                error_message = "*Aleast 8 characters required"
            elif len(credential) > 25 :
                error_message = "*Only 25 characters allowed"
            else:
                return credential,None
            
        elif cred_type == ("Password"):
            if credential == '':
                error_message = "*User Password Required"
            elif credential.count(" ") != 0:
                error_message = "*Password can't have space"
            elif len(credential) < 8 or len(credential) > 25:
                error_message = "*Password must have 8 - 25 characters"                
            else:
                return credential, None
        
        elif cred_type == ("Confirm Password"):
            if credential == '':
                error_message = "*Please Confirm Password"
            else:
                return credential, None

        elif cred_type == ("Website") :
            if credential == '' :
                error_message = "*Website required"
            else:
                return credential,None
        return None, error_message
            
    def hash_master_key(self, master_password, salt):
        return bcrypt.hashpw(master_password.encode(), salt)

    def connect_to_database(self):
        try:
            connection = mysql.connector.connect(**self.db_config)
            if connection.is_connected():
                return connection
        except Error as e:
            self.show_message_box("Connection Error", "Can't connect to Database", QMessageBox.Critical)
            exit

    def initialize_database(self):
        self.db_config = {
            'host': '127.0.0.1',
            'user': 'root',
            'password': 'asdf'
        }
        connection = self.connect_to_database()
        if connection:
            try:                
                cursor = connection.cursor()
                
                # Create the database if it doesn't exist
                cursor.execute("CREATE DATABASE IF NOT EXISTS passwordmanager")
                cursor.execute("USE passwordmanager")

                # Create the Users table if it doesn't exist
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS Users (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        username VARCHAR(255) NOT NULL,
                        salt CHAR(29) NOT NULL,
                        master_key VARCHAR(255) NOT NULL
                    )
                """)

                # Create the Passwords table if it doesn't exist
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS Passwords (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT,
                        website VARCHAR(255) NOT NULL,
                        password VARCHAR(255) NOT NULL,
                        FOREIGN KEY (user_id) REFERENCES Users(id)
                    )
                """)

                connection.commit()
                self.db_config['database'] = 'passwordmanager'
            except Error as e:
                self.show_message_box("Database Error", "Can't Initialize Database", QMessageBox.Critical)
                exit()
            finally:
                cursor.close()
                connection.close()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    main_window_obj = Ui_MainWindow()
    main_window_obj.setupUi(MainWindow)

    register_dialog = QDialog()
    register_dialog_obj = Ui_RegisterDialog()

    signin_dialog = QDialog()
    signin_dialog_obj = Ui_SigninDialog()
    
    main_window_obj.initialize_database()

    MainWindow.show()
    sys.exit(app.exec_())

scripts/qt_main.py
Raqeeb27/CryptWizard