server
import socket
import hmac
import random
from socket import SOL_SOCKET, SO_REUSEADDR
HOST = '127.0.0.1'
PORT = 8080
secret_number = 32
msg = b'liyi'
#secret = random_strs(num)
# 生成一段指定长度的字符串
def random_strs(num):
strs = 'qwertyuiopasdfghjklzxcvbnm'
strs = strs + strs.upper()
strs = strs + '1234567890'
ss = ''
for i in range(num):
s = random.choice(strs)
ss = ss + s
return ss
def main():
sk = socket.socket()
sk.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sk.bind((HOST, PORT))
sk.listen()
conn, addr = sk.accept()
secret = bytes(random_strs(32), encoding='utf-8')
conn.send(secret)
secret_info = conn.recv(len(msg) + secret_number).decode('utf-8')
h = hmac.new(secret, msg, digestmod='MD5')
header = h.hexdigest()
if secret_info == header:
print('客户端合法')
else:
print('客户端不合法')
conn.close()
sk.close()
if __name__ == '__main__':
main()
~~分割线~~---------------------------
------------------------------------
#client
import socket
import hmac
HOST = '127.0.0.1'
PORT = 8080
msg = b'liyi'
lenth = 32
def main():
sk = socket.socket()
address = (HOST, PORT)
sk.connect(address)
recv_info = sk.recv(lenth)
h = hmac.new(recv_info, msg, digestmod='MD5')
secret = bytes(h.hexdigest(), encoding='utf-8')
sk.send(secret)
sk.close()
if __name__ == '__main__':
main()