1、验证客户端的合法性
登录:只要有个性化设计的时候就需要登录
登录和合法性验证二选一,如果做登录的功能就不需要做合法性验证
server
import os
import socket
import hashlib
SECRET_KEY = b'yongliang'
def check_client(conn):
randbytes = os.urandom(32)
conn.send(randbytes)
md5 = hashlib.md5(SECRET_KEY)
md5.update(randbytes)
code = md5.hexdigest()
code_cli = conn.recv(32).decode('utf-8')
return code == code_cli
sk = socket.socket()
sk.bind(('127.0.0.1',9001))
sk.listen()
while True:
conn,addr = sk.accept()
if not check_client(conn):continue
print('进程正常的通信了')
client
import os
import socket
import hashlib
SECRET_KEY = b'yongliang'
def check_client():
randbytes = sk.recv(32)
md5 = hashlib.md5(SECRET_KEY)
md5.update(randbytes)
code = md5.hexdigest().encode('utf-8')
sk.send(code)
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
check_client()
print('正常的客户端通信')
明文进行加密时也可以用 hmac 模块
import os
import hmac
SECRET_KEY = b'yongliang'
randbytes = os.urandom(32)
mac = hmac.new(SECRET_KEY,randbytes)
ret = mac.digest()
print(ret)