‘‘‘认证客户端的链接合法性‘‘‘
# import os, hmac
# secret_key = b‘just so so‘
#
# msg1 = os.urandom(32)
# print(msg1) # 32位随机字节
# print(len(msg1)) # 长度一直为32
#
#
# h = hmac.new(secret_key, msg1, ‘sha256‘)
# print(h.digest()) # md5加密加盐算法,固定长度32字节
# print(len(h.digest())) # 32位
#
# data = b‘客户端发过来的信息‘
# hmac.compare_digest(h.digest(), data) # 判断a==b,a和b必须同一个类型(同为字节或字符串)
import socketserver
import os
import hmac
‘‘‘服务端‘‘‘
secret_key = b‘just so so‘ # 自行设置,用来加盐(md5加盐)
class Myserver(socketserver.BaseRequestHandler):
def handle(self):
msg1 = os.urandom(32) # 随机生成32位字节
self.request.sendall(msg1) # 将随机生成的32位字节发送给客户端
h = hmac.new(secret_key, msg1, ‘sha256‘) # 第三个参数必传入md5加密方式
# print(type(h)) # <class ‘hmac.HMAC‘>
h_digest = h.digest() # 上一步hmac.new()和这一步是一块使用的,目的是让服务端知道收多少个字节的数及与客户端发来的验证做比较
# print(h_digest) # b"\xc5\x86\xfaYG`&\x9b\xa7\xf4apy\xa20m\xec)+l\x96,09\xf3N9\xd2‘\xd3\xfe\xd3"
data = self.request.recv(len(h_digest)) # 收到客户端发来的验证消息
if not hmac.compare_digest(h_digest, data): # hamc.compare_digest(a, b),判断a==b,a和b必须位同一类型(字节或字符串)
print(‘客户端IP%s端口为%s的计算机链接成功...‘ % (self.client_address[0], self.client_address[1]))
print(‘链接不合法,即将断开链接...‘)
self.request.close()
return
print(‘客户端IP%s端口为%s的计算机链接成功...‘ % (self.client_address[0], self.client_address[1]))
print(‘链接合法,即将进入消息循环...‘)
while True:
try:
data1 = self.request.recv(1024)
if not data1: break
print(‘客户端发送的消息是:‘, data1.decode(‘utf-8‘))
self.request.sendall(data1.upper())
except Exception:
break
if __name__ == ‘__main__‘:
s = socketserver.ThreadingTCPServer((‘127.0.0.1‘, 8080), Myserver)
s.serve_forever()
# 另一个模块代码
from socket import *
import hmac
‘‘‘客户端合法链接‘‘‘
secret = b‘just so so‘ # 用作md5加盐
tcp_client = socket(AF_INET, SOCK_STREAM)
tcp_client.connect((‘127.0.0.1‘, 8080))
msg = tcp_client.recv(32)
h = hmac.new(secret, msg, ‘sha256‘)
data = h.digest() # 得到结果是字节类型
tcp_client.sendall(data)
while True:
res = input(‘请输入:‘).strip()
if not res: continue
tcp_client.sendall(res.encode(‘utf-8‘))
res1 = tcp_client.recv(1024)
print(‘服务端回复:‘, res1.decode(‘utf-8‘))
# 另一个模块代码
from socket import *
import hmac
‘‘‘客户端不合法链接‘‘‘
secret = b‘just so so1111‘ # 和服务端不一样,所以无法成功链接
tcp_client = socket(AF_INET, SOCK_STREAM)
tcp_client.connect((‘127.0.0.1‘, 8080))
msg = tcp_client.recv(32)
h = hmac.new(secret, msg, ‘sha256‘)
data = h.digest()
tcp_client.sendall(data)
while True:
res = input(‘请输入:‘).strip()
if not res: continue
tcp_client.sendall(res.encode(‘utf-8‘))
res1 = tcp_client.recv(1024)
print(‘服务端回复:‘, res1.decode(‘utf-8‘))
原文:https://www.cnblogs.com/xuewei95/p/14811712.html