Implement a concurrent tcp agreement with the ciphertext Login socketserver

First digest, the client in the client user name as salt.

Then the secondary server summary, with a fixed salt (you can not let other people know what salt is), then save to file, the encrypted data. Or ciphertext and compare file.

Thus even if the user information is intercepted on the network, and the server is present in the user password file different cipher text.

If you can only digest once (encrypted once), it carried out summary on the server. In summary the client, and as plain text, others can know what your salt Yes.

Knowledge used: network programming, socketserver module, hashlib module encrypts the password, struct module package to solve the sticky problem

#userinfo文件
    zhangsan|5701564ecae32e15698e774d993d6b2306028de0
    lisi|099841fab9a5d7ef090eb725059b9b656efe25e5

#服务端代码:
    import struct
    import socketserver
    import hashlib
    class Myserver(socketserver.BaseRequestHandler):
        def handle(self):
            conn = self.request
            salt = '加盐了'.encode('utf-8')#在服务端设置固定的盐
            while True:
                try:
                    len = conn.recv(4)
                    name_len = struct.unpack('i',len)[0]
                    name = conn.recv(name_len).decode('utf-8')
                    ret = conn.recv(1024).decode('utf-8')

                    sha = hashlib.sha1(salt)  #在服务端加固定的盐
                    sha.update(ret.encode('utf-8'))#对加密后的密码进行二次加密
                    res = sha.hexdigest()

                    with open('userinfo',encoding='utf-8',mode='r') as f:
                        for line in f:
                            line_lst = line.strip().split('|')
                            if name == line_lst[0] and res == line_lst[1]:
                                print('登录成功')
                                conn.send('登录成功'.encode('utf-8'))
                                break
                        else:
                            print('登录失败')
                            conn.send('登录失败'.encode('utf-8'))

                except ConnectionResetError:
                    break
    server = socketserver.ThreadingTCPServer(('192.168.14.91',9003),Myserver)
    server.serve_forever()

#客户端代码:
    import socket
    import struct
    import hashlib

    sk = socket.socket()
    sk.connect(('192.168.14.247',9003))

    name = input('请输入用户名:')  #zhangsan
    password = input('请输入密码:').encode('utf-8') #123456

    sha = hashlib.sha1(name.encode('utf-8'))#针对于每个账户,每个账户的盐都不一样
    sha.update(password)
    ret = sha.hexdigest()

    name_len = struct.pack('i',len(name))
    sk.send(name_len)
    sk.send(name.encode('utf-8'))#发送用户名
    sk.send(ret.encode('utf-8'))#发送摘要后的密码
    msg = sk.recv(1024).decode('utf-8')
    print(msg)

Guess you like

Origin www.cnblogs.com/xiaomage666/p/11011844.html