目的:对连接服务器的客户端进行判断
# Server
import socket
import hmac
import os
secret_key = bytes('tom', encoding='utf-8')
sk = socket.socket()
sk.bind(('127.0.0.1', 8010))
sk.listen()
connect, addr = sk.accept() def check_client(conn):
"""
使用hmac模块进行加密
new(),里面的数据类型要是bytes
:param conn:
:return: True or False
"""
msg = os.urandom(32) # 使用os模块,随机
conn.send(msg)
h = hmac.new(secret_key, msg)
server_digest = h.digest()
client_digest = conn.recv(1024)
return hmac.compare_digest(server_digest, client_digest) ret = check_client(connect)
if ret:
print('该客户端是合法的客户端')
connect.close()
else:
print('该客户端是不合法的客户端')
connect.close()
sk.close()
# client
import socket
import hmac
secret_key = bytes('tom', encoding='utf-8')
sk = socket.socket()
sk.connect(('127.0.0.1', 8010))
msg = sk.recv(1024)
h = hmac.new(secret_key, msg)
client_server = h.digest()
sk.send(client_server)
sk.close()