socket通信中校验客户端的合法性
hmac模块 —— 推荐
# client
from socket import *
import hmac,os
secret_key=b'linhaifeng bang bang bang'
def conn_auth(conn):
'''
验证客户端到服务器的链接
:param conn:
:return:
'''
msg=conn.recv(32)
h=hmac.new(secret_key,msg)
digest=h.digest()
conn.sendall(digest)
def client_handler(ip_port,bufsize=1024):
tcp_socket_client=socket(AF_INET,SOCK_STREAM)
tcp_socket_client.connect(ip_port)
conn_auth(tcp_socket_client)
while True:
data=input('>>: ').strip()
if not data:continue
if data == 'quit':break
tcp_socket_client.sendall(data.encode('utf-8'))
respone=tcp_socket_client.recv(bufsize)
print(respone.decode('utf-8'))
tcp_socket_client.close()
if __name__ == '__main__':
ip_port=('127.0.0.1',9999)
bufsize=1024
client_handler(ip_port,bufsize)
# server
# -*- coding:utf-8 -*-
from socket import *
import hmac,os
secret_key=b'linhaifeng bang bang bang'
def conn_auth(conn):
'''
认证客户端链接
:param conn:
:return:
'''
print('开始验证新链接的合法性')
# 返回一个bytes类型的32字节的随机串
msg_bytes=os.urandom(32)
# 发给客户端
conn.sendall(msg_bytes)
# hmac.new方法
h=hmac.new(secret_key,msg_bytes)
digest=h.digest()
respone=conn.recv(len(digest))
return hmac.compare_digest(respone,digest)
def data_handler(conn,bufsize=1024):
if not conn_auth(conn):
print('该链接不合法,关闭')
conn.close()
return
print('链接合法,开始通信')
while True:
data=conn.recv(bufsize)
if not data:break
conn.sendall(data.upper())
def server_handler(ip_port,bufsize,backlog=5):
'''
只处理链接
:param ip_port:
:return:
'''
tcp_socket_server=socket(AF_INET,SOCK_STREAM)
tcp_socket_server.bind(ip_port)
tcp_socket_server.listen(backlog)
while True:
conn,addr=tcp_socket_server.accept()
print('新连接[%s:%s]' %(addr[0],addr[1]))
data_handler(conn,bufsize)
if __name__ == '__main__':
ip_port=('127.0.0.1',9999)
bufsize=1024
server_handler(ip_port,bufsize)
hashlib方法
# client
import socket
import hashlib
secret_key = b'wanghw'
client = socket.socket()
client.connect(('127.0.0.1'))
# 生成的是固定的32位字节
random_bytes = client.recv(32)
md5 = hashlib.md5(secret_key)
md5.update(random_bytes)
res = md5.hexdigest()
client.send(res.encode('utf-8'))
client.close()
# server
# -*- coding:utf-8 -*-
import os
import socket
import hashlib
## 随机的字节
## 给每一个客户端发一个随机的字符串,来保证即使数据被拦截了,也不能使用这个消息
random_bytes = os.urandom(32)
## 秘钥
secret_key = b'wanghw'
server = socket.socket()
server.bind(('127.0.0.1',9001))
server.listen()
conn,addr = server.accept()
conn.send(random_bytes)
md5 = hashlib.md5(secret_key)
md5.update(random_bytes)
res = md5.hexdigest()
# MD5位32位
# sha1位40位
ret = conn.recv(1024).decode('utf-8')
if ret == res:
print('是合法的客户端')
print('do sth')
else:
print('不合法!')
conn.close()