认证客户端连接合法性
Posted ch2020
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了认证客户端连接合法性相关的知识,希望对你有一定的参考价值。
服务端代码:
1 from socket import * 2 import os, hmac 3 4 secret_key = b‘hello world‘ 5 6 7 def coon_handle(coon): 8 ‘‘‘判断是否为合法客户端‘‘‘ 9 num = os.urandom(32) 10 coon.sendall(num) 11 h = hmac.new(secret_key, num, digestmod=‘md5‘) 12 digest = h.digest() 13 data = coon.recv(len(digest)) 14 return hmac.compare_digest(digest, data) 15 16 17 def data_job(coon): 18 while True: 19 data = coon.recv(1024) 20 print(data.decode()) 21 coon.sendall(data.upper()) 22 23 24 def data_handle(ip_port, buffer_size): 25 tcp_server = socket(AF_INET, SOCK_STREAM) 26 tcp_server.bind(ip_port) 27 tcp_server.listen(buffer_size) 28 while True: 29 coon, addr = tcp_server.accept() 30 print(‘开始验证新连接的合法性‘) 31 try: 32 if coon_handle(coon): 33 print(‘合法接入‘) 34 data_job(coon) 35 else: 36 print(‘非法接入‘) 37 coon.close() 38 continue 39 except Exception as f: 40 print(f) 41 continue 42 43 44 if __name__ == ‘__main__‘: 45 ip_port = ((‘127.0.0.1‘, 8080)) 46 buffer_size = 1024 47 data_handle(ip_port, buffer_size)
服务端代码:
1 from socket import * 2 import hmac 3 4 secret_key = b‘hello world‘ 5 tcp_client = socket(AF_INET, SOCK_STREAM) 6 tcp_client.connect((‘127.0.0.1‘, 8080)) 7 print(‘连接服务器成功,正在验证。。。。‘) 8 msg = tcp_client.recv(1024) 9 h = hmac.new(secret_key, msg, digestmod=‘md5‘) 10 tcp_client.sendall(h.digest()) 11 while True: 12 ms = input(‘亲输入信息‘) 13 tcp_client.sendall(ms.encode()) 14 data = tcp_client.recv(1024) 15 print(data.decode())
以上是关于认证客户端连接合法性的主要内容,如果未能解决你的问题,请参考以下文章