SocketServer模块,hmac模块验证client合法性

Posted gkx0731

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SocketServer模块,hmac模块验证client合法性相关的知识,希望对你有一定的参考价值。

 hmac模块:


1.模块初识:

技术分享图片
import hmac
# h = hmac.new() #括号里要给它连个bytes类型,一个是自定义的secret_key,一个是你想进行加密的bytes
# 密文 = h.digest()
# hmac.compare_digest() #括号内传另外一个密文,看是否相等

h = hmac.new(bsecret,b382835896)
digest = h.digest()
print(digest)
#>>>>  b‘xa4<
xf8xec0x7fx8aoxecxa7(xf7[txfb‘

h = hmac.new(bsecret,b382835896)
digest2 = h.digest()
print(hmac.compare_digest(digest,digest2)) #返回true
hmac模块初识

2.使用hmac模块,验证client端的合法性

技术分享图片
import os
import hmac
import socket
secret_key = bwwl
sk = socket.socket()
sk.bind((127.0.0.1,8080))
sk.listen()
def check_client(conn):
    msg = os.urandom(32)
    conn.send(msg)
    h = hmac.new(secret_key,msg)
    digest = h.digest()
    client_digest = conn.recv(1024)
    return hmac.compare_digest(digest,client_digest)

conn,addr = sk.accept()
res = check_client(conn)
if res:
    print(合法的客户端)
    conn.close()
else:
    print(不合法的客户端)
    conn.close()
sk.close()
server端-hmac
技术分享图片
import socket
import hmac

secret_key = bwwl111
sk = socket.socket()
sk.connect((127.0.0.1,8080))

msg = sk.recv(1024)
h = hmac.new(secret_key,msg)
client_digest = h.digest()
sk.send(client_digest)
sk.close()
client端-hamc

 

 

socketserver模块:


解读socketserver源码 —— http://www.cnblogs.com/Eva-J/p/5081851.html 

socketserver模块可以开启server端的多线程,让多个client端访问server端:

技术分享图片
import socketserver
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):#原来socket写的程序里所有和conn有关的操作,都挪到handle方法里
        #self.request#相当于conn  #一旦客户端断开连接了,handle方法也应该结束
        while True:
            msg = self.request.recv(1024).decode(utf-8)
            if msg == q:break
            print(msg)
            info = input(%s>>>> %msg[:2])
            self.request.send(info.encode(utf-8))

if __name__ == __main__:
    server = socketserver.ThreadingTCPServer((127.0.0.1,8080),MyServer)
    server.serve_forever()
server端-socketserver
技术分享图片
import socket
sk = socket.socket()
sk.connect((127.0.0.1,8080))
while True:
    msg = input(>>>> )
    if msg == q:
        break
    sk.send(msg.encode(utf-8))
    ret = sk.recv(1024).decode(utf-8)
    print(ret)
sk.close()
client端-socketserver

 

以上是关于SocketServer模块,hmac模块验证client合法性的主要内容,如果未能解决你的问题,请参考以下文章

python-41-初识hmac与socketserver模块

33验证客户端的合法性socketserver模块

socketserver hashlib hmac

socketserver hashlib hmac

网络编程- socket协议小结hmac的检验客户端合法性和socketserver模块

网络---29 socketserver模块并发 连接合法性