服务端:
1.secret_key为bytes类型
2.random_bytes = os.urandom(n) 随机生成一个长度为n的random_bytes
server.send(random_bytes)发送给客户端
3.hmac_bytes = hmac(secret_key, random_bytes, ‘md5‘).digest()
通过hmac模块对secret_key和random_bytes进行md5加密,生成一个md5加密后的hmac_bytes
client_hmac_bytes = server.recv(len(hmac_bytes))
接收长度为len(hmac_bytes)的客户端md5加密后的client_hmac_bytes
hmac.compare_digest(hmac_bytes, client_hmac_bytes)
使用hmac.compare_digest()方法对比hmac_bytes和client_hmac_bytes是否一致
客户端:
1.secret_key为bytes类型
2.random_bytes = client.recv(n) 接收长度为n的random_bytes
3.client_hmac_bytes = hmac(secret_key, random_bytes, ‘md5‘).digest()
通过hmac模块对secret_key和random_bytes进行md5加密,生成一个md5加密后的client_hmac_bytes
client.send(client_hmac_bytes) 将client_hmac_bytes发送给服务端
--------------------------------tcp_server.py--------------------------------# coding:utf-8 import os import hmac import socket secret_key = b‘This is my secret key‘ # bytes类型 def conn_auth(conn): random_bytes = os.urandom(32) # 随机生成长度为32字节的bytes conn.send(random_bytes) # 发送给客户端 server_md5_bytes = hmac.new(secret_key, random_bytes, ‘md5‘).digest() # md5加密后的bytes client_md5_bytes = conn.recv(len(server_md5_bytes)) # 接收客户端数据 return hmac.compare_digest(server_md5_bytes, client_md5_bytes) # 对比md5加密后的bytes def data_handler(conn, bufsize=1024): if not conn_auth(conn): print("客户端链接认证失败.") conn.close() return print("客户端链接认证成功.") while 1: client_msg = conn.recv(bufsize) if not client_msg: break print("客户端消息: ", client_msg.decode("utf-8")) conn.send(client_msg.upper()) def server_handler(ip_port, backlog=5): server = socket.socket() server.bind(ip_port) server.listen(backlog) while 1: conn, addr = server.accept() print("客户端链接地址: %s 端口号: %s" % (addr[0], addr[1])) data_handler(conn) conn.close() server.close() if __name__ == ‘__main__‘: ip_port = ("127.0.0.1", 8001) bufsize = 1024 server_handler(ip_port, bufsize)
--------------------------------tcp_client.py--------------------------------# coding:utf-8 import hmac import socket secret_key = b‘This is my secret key.‘ # bytes类型 def conn_auth(conn): server_bytes = conn.recv(32) # 接收来自服务端的随机bytes client_md5_bytes = hmac.new(secret_key, server_bytes, ‘md5‘).digest() # md5加密后的bytes conn.send(client_md5_bytes) # 把md5加密后的bytes发送给服务端 def client_handler(ip_port, bufsize=1024): client = socket.socket() client.connect(ip_port) conn_auth(client) while 1: inp = input(">>>: ").strip() if not inp: continue if inp.upper() == "Q": break client.send(inp.encode("utf-8")) server_msg = client.recv(bufsize) print("服务端消息: ", server_msg.decode("utf-8")) client.close() if __name__ == ‘__main__‘: ip_port = ("127.0.0.1", 8001) bufsize = 1024 client_handler(ip_port, bufsize)
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10945655.html