标签:rev inpu digest self 加密 end nec 分享图片 read
hmac模块:
1.模块初识:
import hmac # h = hmac.new() #括号里要给它连个bytes类型,一个是自定义的secret_key,一个是你想进行加密的bytes # 密文 = h.digest() # hmac.compare_digest() #括号内传另外一个密文,看是否相等 h = hmac.new(b‘secret‘,b‘382835896‘) digest = h.digest() print(digest) #>>>> b‘\xa4<\r\xf8\xec0\x7f\x8ao\xec\xa7(\xf7[t\xfb‘ h = hmac.new(b‘secret‘,b‘382835896‘) digest2 = h.digest() print(hmac.compare_digest(digest,digest2)) #返回true
2.使用hmac模块,验证client端的合法性
import os import hmac import socket secret_key = b‘wwl‘ sk = socket.socket() sk.bind((‘127.0.0.1‘,8080)) sk.listen() def check_client(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_client(conn) if res: print(‘合法的客户端‘) conn.close() else: print(‘不合法的客户端‘) conn.close() sk.close()
import socket import hmac secret_key = b‘wwl111‘ sk = socket.socket() sk.connect((‘127.0.0.1‘,8080)) msg = sk.recv(1024) h = hmac.new(secret_key,msg) client_digest = h.digest() sk.send(client_digest) sk.close()
socketserver模块:
解读socketserver源码 —— http://www.cnblogs.com/Eva-J/p/5081851.html
socketserver模块可以开启server端的多线程,让多个client端访问server端:
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self):#原来socket写的程序里所有和conn有关的操作,都挪到handle方法里 #self.request#相当于conn #一旦客户端断开连接了,handle方法也应该结束 while True: msg = self.request.recv(1024).decode(‘utf-8‘) if msg == ‘q‘:break print(msg) info = input(‘%s>>>> ‘%msg[:2]) self.request.send(info.encode(‘utf-8‘)) if __name__ == ‘__main__‘: server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8080),MyServer) server.serve_forever()
import socket sk = socket.socket() sk.connect((‘127.0.0.1‘,8080)) while True: msg = input(‘>>>> ‘) if msg == ‘q‘: break sk.send(msg.encode(‘utf-8‘)) ret = sk.recv(1024).decode(‘utf-8‘) print(ret) sk.close()
SocketServer模块,hmac模块验证client合法性
标签:rev inpu digest self 加密 end nec 分享图片 read
原文地址:https://www.cnblogs.com/gkx0731/p/9727249.html