网络编程笔记(4)——hmac模块:验证客户端的合法性
内容详细
- hmac-验证客户端的合法性
内容目录
hmac
-
监测一下客户端是否合法
-
不依靠登录认证
import hmac hmac.new() # secret_key,你想进行加密的bytes sercret = h.digest() # 密文 hmac.compare_digest() # 对比 密文与另外一个密文
-
检验客户端连接的可靠性-检查
# Server端: import os import socket import hmac secret_key = b'egg' sk = socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen() def check_conn(conn): msg = os.urandom(32) conn.send(msg) h = hmac.new(secret_key,msg) digest = h.digest() client_digest = conn.recv(1024) return hmac.compare_digest(digest,client_digest) conn,addr = sk.accept() res = check_conn(conn) if res: print('合法的客户端') conn.close() else: print('不合法的客户端') conn.close() sk.close() # Client端: import socket import hmac secret_key = b'egg' sk = socket.socket() sk.connect(('127.0.0.1',8080)) msg = sk.recv(1024) h = hmac.new(secret_key,msg) digest = h.digest() sk.send(digest) sk.close()
-
os.urandom -- 生成一个随机位数的二进制
import os msg = os.urandom(32) print(msg) #b'\xc0\x1c.\xa4\xda\xd3\xd4\xef\xe1`\x8aP\x05}\x9c\x9f\x1f\xa6]\x97NU6\xea\xc3\x01n\xd1\x8f\x1e\x90\x04'
-
socketserver模块--多线程
# server端: import socketserver class MyServer(socketserver.BaseRequestHandler): #必须继承socketserver.BaseRequestHandler这个类 def handle(self): #必须有handle这个方法 # print(self.request.recv(1024)) # self.request相当于conn while True: msg = self.request.recv(1024).decode('utf-8') if msg == 'q': break print(msg) info = input('>>>>') self.request.send(info.encode('utf-8')) if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) # thread 线程 server.serve_forever() # Client端: import socket sk = socket.socket() sk.connect(('127.0.0.1',8080)) while True: msg = input('>>>:') if msg == 'q': sk.send(b'q') break sk.send(msg.encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close()