用hmac验证客户端的合法性

服务器端程序

import os
import hmac
import socket def auth(conn):
secret_key = b'rock'
rand_b = os.urandom(32)
conn.send(rand_b)
obj = hmac.new(secret_key, rand_b)
res1 = obj.digest()
res2 = conn.recv(1024)
cmp_res = hmac.compare_digest(res1, res2)
return cmp_res server = socket.socket()
server.bind(('127.0.0.1', 9000))
server.listen(5) conn, addr = server.accept()
res = auth(conn)
if res:
print('是合法的客户端')
conn.send('你好'.encode())
else:
conn.close() conn.close()
server.close()

客服端程序

import hmac
import socket def auth(client):
secret_key = b'rock'
rand_b = client.recv(32)
obj = hmac.new(secret_key, rand_b)
res2 = obj.digest()
client.send(res2) client = socket.socket()
client.connect(('127.0.0.1', 9000))
auth(client)
msg = client.recv(1024)
print(msg.decode())
client.close()
上一篇:QuartzNet3.0实现作业调度


下一篇:Android Studio 添加已经移除的Module