七. 网络编程(验证客户端合法性 hmac模块)

一. 验证客户端合法性 hmac模块

Python内置的hmac模块实现了标准的Hmac算法,

它利用一个key对message计算“杂凑”后的hash,

使用hmac算法比标准hash算法更安全,因为针对相同的message,不同的key会产生不同的hash。


import
os aa=os.urandom(32) print(type(aa),aa) print("*******************************************************888") import hmac message = b'Hello world' key = b'secret' h = hmac.new(key,message,digestmod="md5") # 第一个参数是密钥key,第二个参数是待加密的字符串,第三个参数是hash函数 print(h.hexdigest()) print("*******************************************************888") 检测 一下客户端是否合法 不依靠登陆认证 import hmac h=hmac.new() # secret_key 你想进行加密的bytes 密文=h.digest() # 密文 # 返回摘要,作为二进制数据字符串值 hmac.compare_digest() # 对比 密文 另外一密文

1.验证客户端合法性

server

import os
import hmac
import socket
secret_key=b'lover'
sk=socket.socket()
sk.bind(('127.0.0.1',8600))
sk.listen()

def chek(conn):
    msg=os.urandom(32)
    conn.send(msg)
    h=hmac.new(secret_key,msg)
    dige=h.digest()

    client_dige=conn.recv(1024)

    return hmac.compare_digest(dige,client_dige)

conn,addr=sk.accept()

res=chek(conn)
if res:
    print("合法的客服端")
    conn.close()
else:
    print("不合法的客服端")
    conn.close()
client

import hmac
import socket
secret_key=b'lover'
sk=socket.socket()
sk.connect(('127.0.0.1',8600))
msg
=sk.recv(1024) h=hmac.new(secret_key,msg) dige=h.digest() sk.send(dige)

猜你喜欢

转载自www.cnblogs.com/Sup-to/p/11141417.html
今日推荐