码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2018-09-30 00:53:15      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:rev   inpu   digest   self   加密   end   nec   分享图片   read   

 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<\r\xf8\xec0\x7f\x8ao\xec\xa7(\xf7[t\xfb‘

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合法性

标签:rev   inpu   digest   self   加密   end   nec   分享图片   read   

原文地址:https://www.cnblogs.com/gkx0731/p/9727249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!