标签:建立 and strip() secret rom digest int back from
一种类似于哈希的加密方式,
服务端建立连接后发送固定的随机数,客户端接收同样的随机数后,
使用这串字符串与客户端的密匙生成hmac数据返回服务端,
服务端自己也用hmac把随机数与服务端密匙生成数据
两个数据用hmac模块的比较即可。
服务端
1 import hmac,os 2 from socket import * 3 4 secret_key = b‘just do it‘ 5 6 def conn_auth(conn): 7 print(‘开始验证链接合法性‘) 8 msg = os.urandom(32) 9 conn.sendall(msg) 10 h = hmac.new(secret_key,msg) 11 digest = h.digest() 12 respone = conn.recv(len(digest)) 13 return hmac.compare_digest(respone,digest) 14 15 16 def data_handler(conn,bufsize): 17 if not conn_auth(conn): 18 print(‘该链接不合法,关闭‘) 19 conn.close() 20 return 21 print(‘链接合法,开始通信‘) 22 while True: 23 data = conn.recv(bufsize) 24 if not data:break 25 conn.sendall(data.upper()) 26 27 28 def server_handlse(ip_port,bufsize,backlog=5): 29 tcp_socket_server = socket(AF_INET,SOCK_STREAM) 30 tcp_socket_server.bind(ip_port) 31 tcp_socket_server.listen(backlog) 32 while 1: 33 conn,addr = tcp_socket_server.accept() 34 print(‘产生新连接‘) 35 data_handler(conn,bufsize) 36 37 if __name__ == ‘__main__‘: 38 ip_port = (‘121.195.167.34‘,9999) 39 bufsize = 1024 40 server_handlse(ip_port,bufsize)
客户端
1 import hmac 2 from socket import * 3 4 secret_key = ‘just do it‘.encode(‘utf-8‘) 5 6 def conn_auth(conn): 7 msg = conn.recv(32) 8 h = hmac.new(secret_key,msg) 9 digest = h.digest() 10 conn.sendall(digest) 11 12 13 14 def client_handler(ip_port, bufsize): 15 tcp_socket_client = socket(AF_INET,SOCK_STREAM) 16 tcp_socket_client.connect(ip_port) 17 18 conn_auth(tcp_socket_client) 19 20 while True: 21 data = input(‘>>>:‘).strip() 22 if data == ‘quit‘: 23 break 24 else: 25 continue 26 tcp_socket_client.sendall(data.encode(‘utf-8‘)) 27 respone = tcp_socket_client.recv(bufsize) 28 print(respone.decode(‘utf-8‘)) 29 tcp_socket_client.close() 30 31 if __name__ == ‘__main__‘: 32 ip_port = (‘121.195.167.34‘,9999) 33 bufsize = 1024 34 client_handler(ip_port,bufsize)
j
标签:建立 and strip() secret rom digest int back from
原文地址:https://www.cnblogs.com/shachengcc1/p/11307362.html