SocketServer模塊,hmac模塊驗證client合法性

 hmac模塊:html


1.模塊初識:多線程

import hmac
# h = hmac.new() #括號裏要給它連個bytes類型,一個是自定義的secret_key,一個是你想進行加密的bytes
# 密文 = h.digest()
# hmac.compare_digest() #括號內傳另一個密文,看是否相等

h = hmac.new(b'secret',b'382835896')
digest = h.digest()
print(digest)
#>>>>  b'\xa4<\r\xf8\xec0\x7f\x8ao\xec\xa7(\xf7[t\xfb'

h = hmac.new(b'secret',b'382835896')
digest2 = h.digest()
print(hmac.compare_digest(digest,digest2)) #返回true
hmac模塊初識

2.使用hmac模塊,驗證client端的合法性dom

import os
import hmac
import socket
secret_key = b'wwl'
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 = b'wwl111'
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模塊:socket


解讀socketserver源碼 —— http://www.cnblogs.com/Eva-J/p/5081851.html ide

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
相關文章
相關標籤/搜索