认证客户端的链接合法性

服务端思路:客户连进来以后,随机生成一个盐,然后发送过去,配合客户端的密钥生成新的摘要,再比对摘要是否相同

#服务端
from socket import *
import hmac,os
server = socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(('127.0.0.1',9999))
server.listen(5)


secret_key = b'chenxing'  #密钥
def proving(conn):  #验证函数,
    print("开始验证")
    msg = os.urandom(32)  #随机生成加盐二进制字符
    conn.sendall(msg)   #将随机生成的盐发送给客户端
    local_secret = hmac.new(secret_key,msg)  #加盐摘要
    digest = local_secret.digest()  #获取摘要,返回的是二进制
    client_secret = conn.recv(len(digest))  #以本地密钥的长度为基准,截取匹配的字符串
    return  hmac.compare_digest(digest,client_secret)  #比较两个二进制是否相同
#此处将这个函数封装的非常好,在多出进行调用
def judge(conn): if not proving(conn): print("该链接不合法") conn.close() return print("该链接合法") while True: ret = conn.recv(1024) if not ret: break print(ret.decode('utf-8')) conn.send(ret.upper()) if __name__ == "__main__": while True: conn,addr = server.accept() #接受链接 print("新连接【%s:%s】"%(addr[0],addr[1])) judge(conn)

如果存在密钥:

from socket import *
import hmac
client = socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',9999))

secret_key = b'chenxing'
def poving():
    msg = client.recv(32)  #先取盐
    local_secret = hmac.new(secret_key,msg)
    disget = local_secret.digest()
    client.send(disget)  #将摘要发过去
poving()
while True:
    data = input(">>>").strip()
    if len(data) == 0:break
    client.send(data.encode('utf-8'))
    ret = client.recv(1024)
    print(ret.decode('utf-8'))
client.close()

 

posted @ 2017-12-20 15:39  明王不动心  阅读(158)  评论(0编辑  收藏  举报