Python socket编程-进阶4
客户端验证的合法性
server:
import socketserver import os, hmac class MyServer(socketserver.BaseRequestHandler): secret_key=b'abcdefg' def handle(self): # 重写handle方法 if not self.auth_conn(): print('客户端验证不合法!') self.request.close() return else: print('客户端验证通过') while True: try: data = self.request.recv(1024) print(data) self.request.sendall('successful'.encode('utf-8')) except Exception as e: print(e) break """ 验证方法: 1. 当客户端连接进来的时候, 先发送 msg = os.urandom(32) 2. 客户端收到后,根据 msg进行 撒盐加密 3. 服务端,自己先加密后然后和客户端的加密内容比对 """ def auth_conn(self): msg = os.urandom(32) # 随机生成32位字节数字 self.request.sendall(msg) h = hmac.new(self.secret_key, msg) # 对数字加密 digest = h.digest() # 打包加密 respone = self.request.recv(len(digest)) return hmac.compare_digest(respone, digest) if __name__ == '__main__': tcp = socketserver.ThreadingTCPServer(('localhost', 8081,), MyServer) tcp.serve_forever()
client:
import socket import hmac,os secret_key=b'abcdefg' def conn_auth(conn): msg=conn.recv(32) h=hmac.new(secret_key,msg) digest=h.digest() conn.sendall(digest) #======================================================================== tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.connect(('localhost', 8081,)) # 通讯之前先验证客户端 conn_auth(tcp) while True: msg = input('客户端:') if not msg: continue tcp.send(msg.encode('utf-8')) msg = tcp.recv(1024) msg = msg.decode('utf-8') print(msg)