[2021-09-19] Information Security Experiment 4 - identity and access security experiment

Who knows how long I've been doing, how many blogs I've read, and how many blogs I've invaded and deleted~

Experiment content 1: Cryptography.exe realizes the function of "MD5 algorithm"

Please refer to the "SHA algorithm" program function and interface in Cryptography.exe to program and realize the desktop program or web program (the development language is not limited, the program has an interface, similar to the figure below) to realize the corresponding "MD5 algorithm" function.

Five point font, do not paste all codes, just paste the core code, and the code shall not exceed 4 pages)

Development environment: Python 3 + pycharm, which directly uses the hashlib Library in Python for encryption

import PySimpleGUI as simpleGui
import datetime
import tkinter as tk
from tkinter import filedialog
import hashlib
import os

def dealOpenMyFile(values,window):
    try:
        context = window['keyFileInput']
        root = tk.Tk()
        root.withdraw()
        # FolderPath=filedialog.askdirectory()  #Use it yourself depending on the situation
        FilePath = filedialog.askopenfilename()
        # print('FolderPath:', FolderPath)
        print('FilePath:', FilePath)
        f = open(FilePath, "r", encoding="utf-8")
        data = f.read()
        print(data)
        context.update(data)
        f.close()
    except Exception as result:
        print("function OpenMyFile Exception caught:%s" % result)

def GetSignNums(values,window):
    try:
        context = values['keyFileInput']
        signOut = window['keySignOut']
        if context.strip() == "":
            simpleGui.popup_error("Tips", "Please enter the content to calculate the summary value first!")
        else:
            md5 = hashlib.md5(context.encode())
            output = md5.hexdigest()  # hexdigest is the hexadecimal data string value
            print(output)
            signOut.update(output)
    except Exception as result:
        print("function GetSignNums Exception caught:%s" % result)

def OutPutSign(values,window):
    print("Click export")
    try:
        SignOut = values['keySignOut']
        if SignOut.strip() == "":
            simpleGui.popup_error("Tips", "No summary value can be exported!")
        else:
            root = tk.Tk()
            root.withdraw()
            print("ook")
            # FolderPath=filedialog.askdirectory()  #Use it yourself depending on the situation
            FilePath = filedialog.askdirectory() + r"/log.txt"
            if os.path.exists(FilePath) == False:  #If the file does not exist, create it
                f = open(FilePath, 'w', encoding="utf-8")
            # print('FolderPath:', FolderPath)
            print('FilePath:', FilePath)
            f = open(FilePath, "w", encoding="utf-8")
            f.write(SignOut)
            print(SignOut)
            simpleGui.popup_error("Tips", "The calculation summary value has been exported to the path you selected log.txt And only the current summary value is saved!")
            f.close()
    except Exception as result:
        print("function OutPutSign Exception caught:%s" % result)

def dealWindow2OkEvent(window2, values):
    newText = ""
    try:
        newText = values['keyWindow2ulText']
        window2.close()
        window2 = None
    except Exception as result:
        print("function dealWindow2Event Exception caught:%s" % result)
    return window2, newText

def main():
    simpleGui.theme("BluePurple")
    try:
        # Create mainWindow layout
        mainWindowLayout = [
            [simpleGui.Text('Input message')],
            [simpleGui.Multiline(key='keyFileInput', size=(80, 4)),
                [simpleGui.Button('File input', key='keyInput'),simpleGui.Button('Reset', key='keyReset')]
            ],
            [simpleGui.Text('Signature summary value')],
            [simpleGui.Multiline(key='keySignOut', size=(80, 4)),
            [simpleGui.Button('Calculate summary value', key='keySign'),simpleGui.Button('Export', key='keyOutput')]],
            [simpleGui.Button('sign out', key='keyMainWindowQuit')]
        ]

        # Create a window, introduce the layout, and initialize it.
        mainWindow = simpleGui.Window('MD5 algorithm(32 Bit lowercase output)', layout=mainWindowLayout, font=("Song typeface",15),finalize=True)

        # Don't create windows2 for now
        window2 = None

        # Create an event loop, otherwise the window will be closed once it runs.
        while True:
            global window
            window, event, values = simpleGui.read_all_windows()
            print(window, event, values)  # You can print and see the contents of the variables
            if window == mainWindow:
                if event in (simpleGui.WIN_CLOSED,  'keyMainWindowQuit'):
                    break
                elif event == 'keyReset':
                    fileInput = window['keyFileInput']
                    fileInput.update("")
                elif event == 'keyInput':
                    #File system, read the contents of the file and put them in the box above
                    dealOpenMyFile(values,window)
                elif event == 'keySign':
                    print("Click calculate summary value")
                    #Calculate the summary value and put it in the box below
                    GetSignNums(values,window)
                elif event == 'keyOutput':
                    #Export the summary value in the box to a txt file, and clear the summary value box
                    OutPutSign(values,window)
            if window == window2:
                if event in (simpleGui.WIN_CLOSED, 'keyWindow2Cancel'):
                    window2.close()
                    window2 = None
                elif event == 'keyWindow2Ok':
                    window2, newText = dealWindow2OkEvent(window2, values)
                    text = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "\n from window2 Get text:\n" + newText
                    mainWindow['keyMainWindowMulText'].update(text)
        # close window
        mainWindow.close()
        if window2 is not None:
            window2.close()
    except Exception as result:
        print("function main Exception caught:%s" % result)

if __name__ == '__main__':
    main()

reference material:

  1. The art of Java encryption and decryption is a good reference book for reference.

Chapter 6 introduces the implementation of hash algorithm in Java. You can refer to the code. See Chapter 06 for the relevant code of MD5_ 1_ 3. rar, more codes can be obtained from "the art of java encryption and decryption - book source code. rar". However, the test code only hashes messages. The program you need to do involves hashing files. You only need to add corresponding file operations.

  1. MD5 encryption - Webmaster tool

http://tool.chinaz.com/Tools/md5.aspx

You can use the above tool to verify whether the program you write is correct.

  1. MD5 decryption MD5 online decryption MD5

http://pmd5.com/

From the running results of this tool, we know that MD5 has been cracked. In fact, SHA-1 has also been cracked.

Operation screenshot:

Experiment content 2: a simple registration and login verification program

Vegetable dog thinks it's not easy at all. Maybe that's why I cook!

In "Chapter 7 authentication. PPT", we talked about how to safely save the user password. See "7.3.4 password verification" for details. This experiment requires you to write a simple registration and login verification program, C/S or B/S, unlimited language, and complete the following functions:

  1. Implementation of the registration module: the user is required to enter the user name and password, and confirm the password. After successful registration, the prompt "successful registration, please log in!" will be prompted. Save the user name, password, ciphertext and salt value into the database, and use simple databases such as access and SQLite. (the salt value is generated randomly, the length is customized, and the combination of salt value and password is customized)

  2. Realize the login verification module: the user enters the user name and password, the program processes them, compares them with the results stored in the database, and judges whether the user name and password are correct. If they are correct, it will prompt "login success", otherwise it will prompt "wrong user name or password".

(five point font, do not paste all codes, just paste the core code, and the code shall not exceed 4 pages)

Development environment: Python 3 + pycharm

I didn't use C/S, B/S or database. I saved the user information in Excel file and wrote two exe s. One was used as Server server and registered on it, and the other was used as Client for login.

Server.py

import PySimpleGUI as simpleGui
import datetime
import tkinter as tk
from tkinter import filedialog
import os
import hashlib #Third party library for generating MD5 encryption password
import random #Third party library for generating random numbers
import xlwt
import xlrd
import time

# Simple version of md5 encryption return ciphertext function
def mymd5(pw):
    md = hashlib.md5()  # Generate md5 object
    md.update(pw.encode('utf-8'))  # When encrypting a password, the password must be encoded, otherwise an error will be reported
    print(md.hexdigest())
    return md.hexdigest()  # Returns the hexadecimal ciphertext


# This is a function for adding salt to the password. By default, 10 digit random number salt is added. The salt adding method is the salt in the second and last 5 digits
def add_salt_md5(pw, n=10):
    salt_list = '`1234567890-=qwertyuiop[]asdfghjklzxcvbnm,.'
    # Generate a random number with a length of 10 (the length of the random number can be customized in the parameter
    # The resulting salt is returned as one of the results

    if n < 4:  # Prevent too few digits of salt, resulting in poor encryption effect
        n = 4
    if pw == '':  # Check whether the password is empty. This can generally be omitted
        return False
    salt = ''.join(random.sample(salt_list, n))
    #The first digit of the original password + the salt value of the first half + all the remaining passwords + the salt value of the second half
    pw = ''.join([pw[0], salt[0: n//2], pw[1:], salt[n//2:]])
    # salt and new password are returned. salt is stored in several databases. The new password is encrypted with mymd5 to generate ciphertext and stored in the database

    workbook = xlrd.open_workbook(r'D:/User database/users.xls')  # Open the specified excel file
    sheet = workbook.sheets()[0]  # Reads the specified sheet table
    value = sheet.cell(0, 0).value  # Row number and column number start from 0

    print("value: " +value)

    work_book = xlwt.Workbook(encoding='utf-8')
    sheet = work_book.add_sheet('user database')
    sheet.write(0, 0, 'User account')
    sheet.write(0, 1, 'salt value')
    sheet.write(0, 2, 'salt Password after')
    sheet.write(1, 0,value)
    sheet.write(1, 1, salt)
    sheet.write(1, 2, pw)
    work_book.save(r'D:/User database/users.xls')
    return salt,pw

def createUser(values,window):
    try:
        username = values['keyUsername']
        password = values['keyPassword']
        surePws = values['keySurePwd']
        if username.strip() == "" or password.strip() == "" or surePws.strip() =="":
            simpleGui.popup_error("Tips", "Please enter user information before registering!")
        elif password.strip() != surePws.strip():
            print(password)
            print(surePws)
            simpleGui.popup_error("Tips", "The two passwords are inconsistent. Please confirm the password!")
        else:
            print("my: " + username)
            simpleGui.popup_notify("The system will automatically save the user account salt Value and salt Password after value processing")
            FilePath = r"D:/User database"
            if not os.path.exists(FilePath): # If the folder does not exist, create the file
                os.mkdir(FilePath)
            work_book = xlwt.Workbook(encoding='utf-8')
            sheet = work_book.add_sheet('user database')
            sheet.write(0, 0, username)
            print(FilePath + r'/users.xls')
            work_book.save(FilePath + r'/users.xls')
            simpleGui.popup_notify("Save to D:/User database/users.xls In the file")
            # print('FolderPath:', FolderPath)
            print('FilePath:', FilePath)
            newPwd = mymd5(password) # The password encrypted by MD5 algorithm is converted to hexadecimal
            add_salt_md5(newPwd, n=10)
            simpleGui.popup_ok("Registration succeeded, please login!")

    except Exception as result:
        print("function createUser Exception caught:%s" % result)

def GetSignNums(values,window):
    try:
        context = values['keyFileInput']
        signOut = window['keySignOut']
        if context.strip() == "":
            simpleGui.popup_error("Tips", "Please enter the content to calculate the summary value first!")
        else:
            md5 = hashlib.md5(context.encode())
            output = md5.hexdigest()  # hexdigest is the hexadecimal data string value
            print(output)
            signOut.update(output)
    except Exception as result:
        print("function GetSignNums Exception caught:%s" % result)

def OutPutSign(values,window):
    print("Click export")
    try:
        SignOut = values['keySignOut']
        if SignOut.strip() == "":
            simpleGui.popup_error("Tips", "No summary value can be exported!")
        else:
            root = tk.Tk()
            root.withdraw()
            print("ook")
            # FolderPath=filedialog.askdirectory()  #Use it yourself depending on the situation
            FilePath = filedialog.askdirectory() + r"/log.txt"
            if os.path.exists(FilePath) == False:  #If the file does not exist, create it
                f = open(FilePath, 'w', encoding="utf-8")
            # print('FolderPath:', FolderPath)
            print('FilePath:', FilePath)
            f = open(FilePath, "w", encoding="utf-8")
            f.write(SignOut)
            print(SignOut)
            simpleGui.popup_error("Tips", "The calculation summary value has been exported to the path you selected log.txt And only the current summary value is saved!")
            f.close()
    except Exception as result:
        print("function OutPutSign Exception caught:%s" % result)

def dealWindow2OkEvent(window2, values):
    newText = ""
    try:
        newText = values['keyWindow2ulText']
        window2.close()
        window2 = None
    except Exception as result:
        print("function dealWindow2Event Exception caught:%s" % result)
    return window2, newText

def main():
    global window, salt, pw, username
    username = ""
    simpleGui.theme("BluePurple")
    try:
        # Create mainWindow layout
        mainWindowLayout = [
            [simpleGui.Text('User account:'), simpleGui.Input(key='keyUsername', size=(80, 1)), ],
            [simpleGui.Text('User password:'), simpleGui.Input(key='keyPassword', size=(80, 1)), ],
            [simpleGui.Text('Confirm password:'), simpleGui.Input(key='keySurePwd', size=(80, 1)), ],
            [simpleGui.Button('Reset', key='keyReset'), simpleGui.Button('register', key='keyRegister')]
        ]

        # Create a window, introduce the layout, and initialize it.
        mainWindow = simpleGui.Window("Registration module", layout=mainWindowLayout, font=("Song typeface",15),finalize=True,element_justification="center")

        # Don't create windows2 for now
        window2 = None

        # Create an event loop, otherwise the window will be closed once it runs.
        while True:
            window, event, values = simpleGui.read_all_windows()
            print(window, event, values)  # You can print and see the contents of the variables
            if window == mainWindow:
                if event == simpleGui.WIN_CLOSED:
                    break
                elif event == 'keyReset':
                    username = window['keyUsername']
                    password = window['keyPassword']
                    surePwd = window['keySurePwd']
                    username.update("")
                    password.update("")
                    surePwd.update("")
                elif event == 'keyRegister':
                    #Save the user account and password in the database. In order to simplify the operation, I put them in the file
                    createUser(values,window)
            if window == window2:
                if event in (simpleGui.WIN_CLOSED, 'keyWindow2Cancel'):
                    window2.close()
                    window2 = None
                elif event == 'keyWindow2Ok':
                    window2, newText = dealWindow2OkEvent(window2, values)
                    text = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "\n from window2 Get text:\n" + newText
                    mainWindow['keyMainWindowMulText'].update(text)
        # close window
        mainWindow.close()
        if window2 is not None:
            window2.close()
    except Exception as result:
        print("function main Exception caught:%s" % result)

if __name__ == '__main__':
    main()

Client.py

import PySimpleGUI as simpleGui
import datetime
import xlrd
import Server

def isRealUser(values,window):
    try:
        uname = values['keyUsername']
        pwd = values['keyPassword']
        pwd = Server.mymd5(pwd)
        print("This input:" + pwd)
        #Read the salt value in the xls file and the password after salt value processing
        workbook = xlrd.open_workbook(r'D:/User database/users.xls')  # Open the specified excel file
        sheet = workbook.sheets()[0]  # Reads the specified sheet table
        salt = sheet.cell(1, 1).value  # Row number and column number start from 0
        salt_password = sheet.cell(1, 2).value  # Row number and column number start from 0
        print("In the file salt: " + salt)
        print("Password in file:" + salt_password)
        myPass = ''.join([pwd[0], salt[0: 10//2], pwd[1:], salt[10//2:]])
        print("After treatment:" + myPass)
        if myPass == salt_password:
            simpleGui.popup_ok("Login succeeded")
        else:
            simpleGui.popup_error("Wrong user name or password")
    except Exception as result:
        print("function OpenMyFile Exception caught:%s" % result)

def dealWindow2OkEvent(window2, values):
    newText = ""
    try:
        newText = values['keyWindow2ulText']
        window2.close()
        window2 = None
    except Exception as result:
        print("function dealWindow2Event Exception caught:%s" % result)
    return window2, newText

def main():
    simpleGui.theme("BluePurple")
    try:
        # Create mainWindow layout
        mainWindowLayout = [
            [simpleGui.Text('User account:'), simpleGui.Input(key='keyUsername', size=(80, 1)), ],
            [simpleGui.Text('User password:'), simpleGui.Input(key='keyPassword', size=(80, 1)), ],
            [simpleGui.Button('Reset', key='keyReset'),simpleGui.Button('Sign in', key='keyLogin')]
        ]

        # Create a window, introduce the layout, and initialize it.
        mainWindow = simpleGui.Window('Client Login authentication module', layout=mainWindowLayout, font=("Song typeface",15),finalize=True,element_justification="center")

        # Don't create windows2 for now
        window2 = None

        # Create an event loop, otherwise the window will be closed once it runs.
        while True:
            global window
            window, event, values = simpleGui.read_all_windows()
            print(window, event, values)  # You can print and see the contents of the variables
            if window == mainWindow:
                if event == simpleGui.WIN_CLOSED:
                    print("sign out")
                    break
                if event == 'keyReset':
                    print("Click Reset")
                    username = window['keyUsername']
                    password = window['keyPassword']
                    username.update("")
                    password.update("")
                elif event == 'keyLogin':
                    #Functions that authenticate users
                    isRealUser(values,window)
                else:
                    pass
            if window == window2:
                if event in (simpleGui.WIN_CLOSED, 'keyWindow2Cancel'):
                    window2.close()
                    window2 = None
                elif event == 'keyWindow2Ok':
                    window2, newText = dealWindow2OkEvent(window2, values)
                    text = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "\n from window2 Get text:\n" + newText
                    mainWindow['keyMainWindowMulText'].update(text)
        # close window
        mainWindow.close()
        if window2 is not None:
            window2.close()
    except Exception as result:
        print("function main Exception caught:%s" % result)

if __name__ == '__main__':
    main()

Tags: Python Pycharm

Posted on Mon, 20 Sep 2021 03:18:03 -0400 by jrschwartz