Objective: to connect the server determines the client
# 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): "" " use hmac module encrypted new (), if the data type which bytes : param Conn: : return: True or False " "" MSG = OS. urandom(32) # Os module may randomly 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 ( ' the client is a legitimate client ' ) connect.close () the else : Print ( ' the client is not legitimate client ' ) 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()