基础本地测试通过,shell改进
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
+77
-46
@@ -1,62 +1,93 @@
|
||||
|
||||
import os
|
||||
import hashlib
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
class File:
|
||||
def __init__(self, file_path, chunk_size=2048):
|
||||
class FileHandler:
|
||||
def __init__(self, file_path: str, chunk_size: int = 2048):
|
||||
self.file_path = file_path
|
||||
self.chunk_size = chunk_size
|
||||
|
||||
def split_to_chunks(self):
|
||||
|
||||
def validate_file_exists(self) -> bool:
|
||||
"""验证文件是否存在"""
|
||||
return os.path.exists(self.file_path)
|
||||
|
||||
def split_to_chunks(self) -> List[bytes]:
|
||||
"""将文件分割为指定大小的块"""
|
||||
chunks = []
|
||||
with open(self.file_path, 'rb') as f:
|
||||
while True:
|
||||
chunk = f.read(self.chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
return chunks
|
||||
|
||||
def read_file(self):
|
||||
"""读取整个文件为二进制数据"""
|
||||
with open(self.file_path, 'rb') as f:
|
||||
return f.read()
|
||||
|
||||
def save_file(self, data, output_path=None):
|
||||
"""保存数据到文件"""
|
||||
if output_path is None:
|
||||
output_path = self.file_path
|
||||
if not self.validate_file_exists():
|
||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
||||
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
with open(output_path, 'wb') as f:
|
||||
f.write(data)
|
||||
return output_path
|
||||
chunks = []
|
||||
try:
|
||||
with open(self.file_path, 'rb') as f:
|
||||
while True:
|
||||
chunk = f.read(self.chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
return chunks
|
||||
except IOError as e:
|
||||
raise IOError(f"读取文件失败: {e}")
|
||||
|
||||
def get_file_info(self):
|
||||
def read_file(self) -> bytes:
|
||||
"""读取整个文件为二进制数据"""
|
||||
if not self.validate_file_exists():
|
||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
||||
|
||||
try:
|
||||
with open(self.file_path, 'rb') as f:
|
||||
return f.read()
|
||||
except IOError as e:
|
||||
raise IOError(f"读取文件失败: {e}")
|
||||
|
||||
def save_file(self, data: bytes, output_path: Optional[str] = None) -> str:
|
||||
"""保存数据到文件"""
|
||||
save_path = output_path or self.file_path
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
with open(save_path, 'wb') as f:
|
||||
f.write(data)
|
||||
return save_path
|
||||
except IOError as e:
|
||||
raise IOError(f"保存文件失败: {e}")
|
||||
|
||||
def get_file_info(self) -> Optional[Dict[str, Any]]:
|
||||
"""获取文件信息"""
|
||||
if not os.path.exists(self.file_path):
|
||||
if not self.validate_file_exists():
|
||||
return None
|
||||
|
||||
file_size = os.path.getsize(self.file_path)
|
||||
file_hash = self.calculate_hash()
|
||||
|
||||
return {
|
||||
'path': self.file_path,
|
||||
'size': file_size,
|
||||
'hash': file_hash,
|
||||
'chunks_count': (file_size + self.chunk_size - 1) // self.chunk_size
|
||||
}
|
||||
try:
|
||||
file_size = os.path.getsize(self.file_path)
|
||||
file_hash = self.calculate_hash()
|
||||
|
||||
return {
|
||||
'path': self.file_path,
|
||||
'size': file_size,
|
||||
'hash': file_hash,
|
||||
'chunks_count': (file_size + self.chunk_size - 1) // self.chunk_size,
|
||||
'chunk_size': self.chunk_size
|
||||
}
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"获取文件信息失败: {e}")
|
||||
|
||||
def calculate_hash(self):
|
||||
"""计算文件SHA256哈希值"""
|
||||
sha256_hash = hashlib.sha256()
|
||||
with open(self.file_path, "rb") as f:
|
||||
for byte_block in iter(lambda: f.read(4096), b""):
|
||||
sha256_hash.update(byte_block)
|
||||
return sha256_hash.hexdigest()
|
||||
def calculate_hash(self, algorithm: str = 'sha256') -> str:
|
||||
"""计算文件哈希值"""
|
||||
if not self.validate_file_exists():
|
||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
||||
|
||||
hash_func = getattr(hashlib, algorithm)()
|
||||
|
||||
try:
|
||||
with open(self.file_path, "rb") as f:
|
||||
for byte_block in iter(lambda: f.read(4096), b""):
|
||||
hash_func.update(byte_block)
|
||||
return hash_func.hexdigest()
|
||||
except IOError as e:
|
||||
raise IOError(f"计算哈希失败: {e}")
|
||||
|
||||
@staticmethod
|
||||
def combine_chunks(chunks):
|
||||
def combine_chunks(chunks: List[bytes]) -> bytes:
|
||||
"""合并数据块为完整文件"""
|
||||
if not chunks:
|
||||
raise ValueError("数据块列表为空")
|
||||
return b''.join(chunks)
|
||||
|
||||
+141
-146
@@ -1,125 +1,119 @@
|
||||
|
||||
import socket
|
||||
import threading
|
||||
import struct
|
||||
import time
|
||||
from typing import Callable, Optional, Tuple
|
||||
from typing import Callable, Optional, Tuple, Dict, List
|
||||
import logging
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TCPIPv6Transporter:
|
||||
def __init__(self):
|
||||
self.servers = {} # 存储服务器socket {port: socket}
|
||||
def __init__(self, timeout: int = 30, chunk_size: int = 4096):
|
||||
self.servers: Dict[int, socket.socket] = {}
|
||||
self.is_listening = False
|
||||
self.receive_callback = None
|
||||
self.receive_callback: Optional[Callable] = None
|
||||
self.timeout = timeout
|
||||
self.chunk_size = chunk_size
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def send_file(self, file_data: bytes, target_ip: str, target_port: int) -> Tuple[bool, str]:
|
||||
def _create_socket(self) -> socket.socket:
|
||||
"""创建IPv6 TCP socket"""
|
||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
return sock
|
||||
|
||||
def send_data(self, data: bytes, target_ip: str, target_port: int) -> Tuple[bool, str]:
|
||||
"""
|
||||
发送文件到指定IPv6地址和端口
|
||||
发送数据到指定IPv6地址和端口
|
||||
"""
|
||||
if not data:
|
||||
return False, "数据为空"
|
||||
|
||||
Args:
|
||||
file_data: 要发送的文件数据
|
||||
target_ip: 目标IPv6地址
|
||||
target_port: 目标端口
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否成功, 错误信息)
|
||||
"""
|
||||
try:
|
||||
# 创建IPv6 TCP socket
|
||||
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
|
||||
# 设置超时时间
|
||||
sock.settimeout(30)
|
||||
with self._create_socket() as sock:
|
||||
sock.settimeout(self.timeout)
|
||||
|
||||
print(f"连接到 [{target_ip}]:{target_port}...")
|
||||
|
||||
# 连接到目标
|
||||
logger.info(f"连接到 [{target_ip}]:{target_port}...")
|
||||
sock.connect((target_ip, target_port, 0, 0))
|
||||
print("连接成功")
|
||||
logger.info("连接成功")
|
||||
|
||||
# 发送数据长度(8字节,大端序)
|
||||
data_length = len(file_data)
|
||||
# 发送数据长度
|
||||
data_length = len(data)
|
||||
sock.send(struct.pack('!Q', data_length))
|
||||
|
||||
# 发送实际数据
|
||||
# 发送数据
|
||||
total_sent = 0
|
||||
chunk_size = 4096
|
||||
|
||||
while total_sent < data_length:
|
||||
# 计算本次发送的数据量
|
||||
remaining = data_length - total_sent
|
||||
send_size = min(chunk_size, remaining)
|
||||
send_size = min(self.chunk_size, remaining)
|
||||
|
||||
# 发送数据块
|
||||
sent = sock.send(file_data[total_sent:total_sent + send_size])
|
||||
sent = sock.send(data[total_sent:total_sent + send_size])
|
||||
if sent == 0:
|
||||
raise ConnectionError("连接中断")
|
||||
|
||||
total_sent += sent
|
||||
|
||||
# 显示进度
|
||||
progress = (total_sent / data_length) * 100
|
||||
if total_sent % (chunk_size * 10) == 0 or total_sent == data_length:
|
||||
print(f"发送进度: {progress:.1f}% ({total_sent}/{data_length} bytes)")
|
||||
# 进度显示
|
||||
if total_sent % (self.chunk_size * 10) == 0 or total_sent == data_length:
|
||||
progress = (total_sent / data_length) * 100
|
||||
logger.info(f"发送进度: {progress:.1f}% ({total_sent}/{data_length} bytes)")
|
||||
|
||||
print("文件发送完成")
|
||||
logger.info("数据发送完成")
|
||||
return True, "发送成功"
|
||||
|
||||
except socket.timeout:
|
||||
error_msg = "连接超时"
|
||||
print(error_msg)
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
except ConnectionRefusedError:
|
||||
error_msg = "连接被拒绝,目标可能未启动服务"
|
||||
print(error_msg)
|
||||
error_msg = "连接被拒绝"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
except Exception as e:
|
||||
error_msg = f"发送失败: {e}"
|
||||
print(error_msg)
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
def start_server(self, listen_port: int, callback: Callable) -> Tuple[bool, str]:
|
||||
"""
|
||||
启动TCP服务器监听指定端口
|
||||
|
||||
Args:
|
||||
listen_port: 监听端口
|
||||
callback: 接收到数据时的回调函数
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否成功, 错误信息)
|
||||
"""
|
||||
if listen_port in self.servers:
|
||||
return False, f"端口 {listen_port} 已经在监听中"
|
||||
|
||||
try:
|
||||
# 创建IPv6 TCP socket
|
||||
server_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
with self.lock:
|
||||
if listen_port in self.servers:
|
||||
return False, f"端口 {listen_port} 已经在监听中"
|
||||
|
||||
# 绑定到所有IPv6地址
|
||||
server_socket.bind(('::', listen_port))
|
||||
server_socket.listen(5)
|
||||
|
||||
self.servers[listen_port] = server_socket
|
||||
self.receive_callback = callback
|
||||
self.is_listening = True
|
||||
|
||||
print(f"服务器开始监听端口 {listen_port}")
|
||||
|
||||
# 启动监听线程
|
||||
thread = threading.Thread(target=self._accept_connections, args=(listen_port,))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return True, f"服务器启动成功,监听端口 {listen_port}"
|
||||
|
||||
except PermissionError:
|
||||
error_msg = f"权限不足,无法监听端口 {listen_port}"
|
||||
print(error_msg)
|
||||
return False, error_msg
|
||||
except Exception as e:
|
||||
error_msg = f"启动服务器失败: {e}"
|
||||
print(error_msg)
|
||||
return False, error_msg
|
||||
try:
|
||||
server_socket = self._create_socket()
|
||||
server_socket.bind(('::', listen_port))
|
||||
server_socket.listen(5)
|
||||
|
||||
self.servers[listen_port] = server_socket
|
||||
self.receive_callback = callback
|
||||
self.is_listening = True
|
||||
|
||||
logger.info(f"服务器开始监听端口 {listen_port}")
|
||||
|
||||
# 启动监听线程
|
||||
thread = threading.Thread(
|
||||
target=self._accept_connections,
|
||||
args=(listen_port,),
|
||||
daemon=True,
|
||||
name=f"Server-{listen_port}"
|
||||
)
|
||||
thread.start()
|
||||
|
||||
return True, f"服务器启动成功,监听端口 {listen_port}"
|
||||
|
||||
except PermissionError:
|
||||
error_msg = f"权限不足,无法监听端口 {listen_port}"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
except Exception as e:
|
||||
error_msg = f"启动服务器失败: {e}"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
def _accept_connections(self, port: int):
|
||||
"""接受连接请求"""
|
||||
@@ -129,105 +123,103 @@ class TCPIPv6Transporter:
|
||||
|
||||
try:
|
||||
while self.is_listening:
|
||||
print(f"等待连接在端口 {port}...")
|
||||
logger.info(f"等待连接在端口 {port}...")
|
||||
client_socket, client_addr = server_socket.accept()
|
||||
|
||||
print(f"接收到来自 [{client_addr[0]}]:{client_addr[1]} 的连接")
|
||||
logger.info(f"接收到来自 [{client_addr[0]}]:{client_addr[1]} 的连接")
|
||||
|
||||
# 处理客户端连接
|
||||
client_thread = threading.Thread(
|
||||
target=self._handle_client,
|
||||
args=(client_socket, client_addr)
|
||||
args=(client_socket, client_addr),
|
||||
daemon=True,
|
||||
name=f"Client-{client_addr[0]}:{client_addr[1]}"
|
||||
)
|
||||
client_thread.daemon = True
|
||||
client_thread.start()
|
||||
|
||||
except OSError:
|
||||
# 正常关闭时的错误
|
||||
pass
|
||||
except Exception as e:
|
||||
if self.is_listening:
|
||||
print(f"接受连接错误: {e}")
|
||||
logger.error(f"接受连接错误: {e}")
|
||||
|
||||
def _handle_client(self, client_socket: socket.socket, client_addr: Tuple):
|
||||
"""处理客户端连接"""
|
||||
try:
|
||||
# 设置超时时间
|
||||
client_socket.settimeout(30)
|
||||
client_socket.settimeout(self.timeout)
|
||||
|
||||
# 接收数据长度(8字节,大端序)
|
||||
length_data = client_socket.recv(8)
|
||||
if not length_data or len(length_data) != 8:
|
||||
raise ValueError("无效的数据长度信息")
|
||||
# 接收数据长度
|
||||
length_data = self._receive_all(client_socket, 8)
|
||||
if not length_data:
|
||||
raise ValueError("未接收到数据长度信息")
|
||||
|
||||
data_length = struct.unpack('!Q', length_data)[0]
|
||||
print(f"准备接收 {data_length} bytes 数据")
|
||||
logger.info(f"准备接收 {data_length} bytes 数据")
|
||||
|
||||
# 接收实际数据
|
||||
received_data = b''
|
||||
total_received = 0
|
||||
chunk_size = 4096
|
||||
# 接收数据
|
||||
received_data = self._receive_all(client_socket, data_length)
|
||||
|
||||
while total_received < data_length:
|
||||
# 计算本次接收的数据量
|
||||
remaining = data_length - total_received
|
||||
recv_size = min(chunk_size, remaining)
|
||||
|
||||
# 接收数据块
|
||||
chunk = client_socket.recv(recv_size)
|
||||
if not chunk:
|
||||
raise ConnectionError("连接中断")
|
||||
|
||||
received_data += chunk
|
||||
total_received += len(chunk)
|
||||
|
||||
# 显示进度
|
||||
progress = (total_received / data_length) * 100
|
||||
if total_received % (chunk_size * 10) == 0 or total_received == data_length:
|
||||
print(f"接收进度: {progress:.1f}% ({total_received}/{data_length} bytes)")
|
||||
logger.info("数据接收完成")
|
||||
|
||||
print("文件接收完成")
|
||||
|
||||
# 调用回调函数处理接收到的数据
|
||||
# 调用回调函数
|
||||
if self.receive_callback:
|
||||
self.receive_callback(received_data, client_addr)
|
||||
else:
|
||||
print("警告: 未设置接收回调函数")
|
||||
logger.warning("未设置接收回调函数")
|
||||
|
||||
except socket.timeout:
|
||||
print("接收数据超时")
|
||||
logger.error("接收数据超时")
|
||||
except Exception as e:
|
||||
print(f"处理客户端数据错误: {e}")
|
||||
logger.error(f"处理客户端数据错误: {e}")
|
||||
finally:
|
||||
client_socket.close()
|
||||
try:
|
||||
client_socket.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
def _receive_all(self, sock: socket.socket, length: int) -> bytes:
|
||||
"""接收指定长度的数据"""
|
||||
data = b''
|
||||
while len(data) < length:
|
||||
chunk = sock.recv(min(self.chunk_size, length - len(data)))
|
||||
if not chunk:
|
||||
raise ConnectionError("连接中断")
|
||||
data += chunk
|
||||
|
||||
# 进度显示
|
||||
if len(data) % (self.chunk_size * 10) == 0 or len(data) == length:
|
||||
progress = (len(data) / length) * 100
|
||||
logger.info(f"接收进度: {progress:.1f}% ({len(data)}/{length} bytes)")
|
||||
|
||||
return data
|
||||
|
||||
def stop_server(self, port: int) -> Tuple[bool, str]:
|
||||
"""
|
||||
停止指定端口的服务器
|
||||
|
||||
Args:
|
||||
port: 要停止的端口
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否成功, 错误信息)
|
||||
"""
|
||||
if port not in self.servers:
|
||||
return False, f"端口 {port} 未在监听中"
|
||||
|
||||
try:
|
||||
server_socket = self.servers[port]
|
||||
server_socket.close()
|
||||
del self.servers[port]
|
||||
with self.lock:
|
||||
if port not in self.servers:
|
||||
return False, f"端口 {port} 未在监听中"
|
||||
|
||||
# 如果所有服务器都停止了,设置监听标志为False
|
||||
if not self.servers:
|
||||
self.is_listening = False
|
||||
|
||||
return True, f"端口 {port} 服务器已停止"
|
||||
except Exception as e:
|
||||
return False, f"停止服务器失败: {e}"
|
||||
try:
|
||||
server_socket = self.servers[port]
|
||||
server_socket.close()
|
||||
del self.servers[port]
|
||||
|
||||
if not self.servers:
|
||||
self.is_listening = False
|
||||
|
||||
logger.info(f"端口 {port} 服务器已停止")
|
||||
return True, f"端口 {port} 服务器已停止"
|
||||
except Exception as e:
|
||||
error_msg = f"停止服务器失败: {e}"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
def stop_all_servers(self) -> Tuple[bool, str]:
|
||||
"""停止所有服务器"""
|
||||
success_count = 0
|
||||
error_count = 0
|
||||
error_msgs = []
|
||||
|
||||
ports = list(self.servers.keys())
|
||||
@@ -236,18 +228,21 @@ class TCPIPv6Transporter:
|
||||
if success:
|
||||
success_count += 1
|
||||
else:
|
||||
error_count += 1
|
||||
error_msgs.append(msg)
|
||||
|
||||
if error_count == 0:
|
||||
return True, f"成功停止 {success_count} 个服务器"
|
||||
if error_msgs:
|
||||
return False, f"成功停止 {success_count} 个,失败 {len(error_msgs)} 个: {', '.join(error_msgs)}"
|
||||
else:
|
||||
return False, f"成功停止 {success_count} 个,失败 {error_count} 个: {', '.join(error_msgs)}"
|
||||
return True, f"成功停止 {success_count} 个服务器"
|
||||
|
||||
def get_listening_ports(self) -> list:
|
||||
def get_listening_ports(self) -> List[int]:
|
||||
"""获取当前正在监听的端口列表"""
|
||||
return list(self.servers.keys())
|
||||
|
||||
def is_port_listening(self, port: int) -> bool:
|
||||
"""检查指定端口是否在监听中"""
|
||||
return port in self.servers
|
||||
|
||||
def __del__(self):
|
||||
"""析构函数,清理资源"""
|
||||
self.stop_all_servers()
|
||||
|
||||
+136
-119
@@ -1,25 +1,59 @@
|
||||
|
||||
|
||||
import os
|
||||
from typing import List, Tuple
|
||||
from cryptography.hazmat.primitives import serialization, hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
import logging
|
||||
|
||||
class RSACrypto:
|
||||
# RSA加密的最大数据块大小(2048位密钥)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class RSACryptoManager:
|
||||
# RSA加密配置
|
||||
KEY_SIZE = 2048
|
||||
MAX_BLOCK_SIZE = 190 # 2048/8 - 42(填充开销)
|
||||
|
||||
ENCRYPTED_BLOCK_SIZE = 256 # 2048/8
|
||||
|
||||
@staticmethod
|
||||
def load_public_key(public_key_path):
|
||||
"""
|
||||
从文件加载公钥
|
||||
|
||||
Args:
|
||||
public_key_path: 公钥文件路径
|
||||
def generate_key_pair(private_key_path: str, public_key_path: str) -> Tuple[bool, str]:
|
||||
"""生成RSA密钥对"""
|
||||
try:
|
||||
private_key = rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=RSACryptoManager.KEY_SIZE,
|
||||
backend=default_backend()
|
||||
)
|
||||
|
||||
Returns:
|
||||
PublicKey: 加载的公钥对象
|
||||
"""
|
||||
# 保存私钥
|
||||
with open(private_key_path, 'wb') as f:
|
||||
f.write(private_key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption()
|
||||
))
|
||||
|
||||
# 保存公钥
|
||||
public_key = private_key.public_key()
|
||||
with open(public_key_path, 'wb') as f:
|
||||
f.write(public_key.public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
))
|
||||
|
||||
logger.info(f"密钥对生成成功: 私钥 {private_key_path}, 公钥 {public_key_path}")
|
||||
return True, "密钥对生成成功"
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"生成密钥对失败: {e}"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
@staticmethod
|
||||
def load_public_key(public_key_path: str):
|
||||
"""从文件加载公钥"""
|
||||
if not os.path.exists(public_key_path):
|
||||
raise FileNotFoundError(f"公钥文件不存在: {public_key_path}")
|
||||
|
||||
try:
|
||||
with open(public_key_path, 'rb') as f:
|
||||
pem_data = f.read()
|
||||
@@ -31,16 +65,11 @@ class RSACrypto:
|
||||
raise ValueError(f"加载公钥失败: {e}")
|
||||
|
||||
@staticmethod
|
||||
def load_private_key(private_key_path):
|
||||
"""
|
||||
从文件加载私钥
|
||||
def load_private_key(private_key_path: str):
|
||||
"""从文件加载私钥"""
|
||||
if not os.path.exists(private_key_path):
|
||||
raise FileNotFoundError(f"私钥文件不存在: {private_key_path}")
|
||||
|
||||
Args:
|
||||
private_key_path: 私钥文件路径
|
||||
|
||||
Returns:
|
||||
PrivateKey: 加载的私钥对象
|
||||
"""
|
||||
try:
|
||||
with open(private_key_path, 'rb') as f:
|
||||
pem_data = f.read()
|
||||
@@ -53,84 +82,61 @@ class RSACrypto:
|
||||
raise ValueError(f"加载私钥失败: {e}")
|
||||
|
||||
@staticmethod
|
||||
def encrypt_block(block_data, public_key_path):
|
||||
"""
|
||||
使用公钥加密单个数据块
|
||||
def encrypt_data(data: bytes, public_key_path: str) -> bytes:
|
||||
"""加密数据"""
|
||||
if not data:
|
||||
raise ValueError("数据为空")
|
||||
|
||||
Args:
|
||||
block_data: 要加密的数据块(不超过190字节)
|
||||
public_key_path: 公钥文件路径
|
||||
|
||||
Returns:
|
||||
bytes: 加密后的数据块
|
||||
"""
|
||||
# 验证数据块大小
|
||||
if len(block_data) > RSACrypto.MAX_BLOCK_SIZE:
|
||||
raise ValueError(f"数据块大小超过限制: {len(block_data)} > {RSACrypto.MAX_BLOCK_SIZE}")
|
||||
# 分割数据为适合RSA加密的块
|
||||
blocks = []
|
||||
for i in range(0, len(data), RSACryptoManager.MAX_BLOCK_SIZE):
|
||||
block = data[i:i + RSACryptoManager.MAX_BLOCK_SIZE]
|
||||
blocks.append(block)
|
||||
|
||||
# 加载公钥
|
||||
public_key = RSACrypto.load_public_key(public_key_path)
|
||||
# 加密所有块
|
||||
encrypted_blocks = RSACryptoManager.encrypt_blocks(blocks, public_key_path)
|
||||
|
||||
# 加密数据块
|
||||
try:
|
||||
encrypted_block = public_key.encrypt(
|
||||
block_data,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
return encrypted_block
|
||||
except Exception as e:
|
||||
raise ValueError(f"加密数据块失败: {e}")
|
||||
# 合并加密后的块
|
||||
return b''.join(encrypted_blocks)
|
||||
|
||||
@staticmethod
|
||||
def decrypt_block(encrypted_block, private_key_path):
|
||||
"""
|
||||
使用私钥解密单个数据块
|
||||
def decrypt_data(encrypted_data: bytes, private_key_path: str) -> bytes:
|
||||
"""解密数据"""
|
||||
if not encrypted_data:
|
||||
raise ValueError("加密数据为空")
|
||||
|
||||
Args:
|
||||
encrypted_block: 加密的数据块
|
||||
private_key_path: 私钥文件路径
|
||||
|
||||
Returns:
|
||||
bytes: 解密后的原始数据块
|
||||
"""
|
||||
# 加载私钥
|
||||
private_key = RSACrypto.load_private_key(private_key_path)
|
||||
# 验证加密数据长度
|
||||
if len(encrypted_data) % RSACryptoManager.ENCRYPTED_BLOCK_SIZE != 0:
|
||||
raise ValueError("无效的加密数据长度")
|
||||
|
||||
# 解密数据块
|
||||
try:
|
||||
decrypted_block = private_key.decrypt(
|
||||
encrypted_block,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
return decrypted_block
|
||||
except Exception as e:
|
||||
raise ValueError(f"解密数据块失败: {e}")
|
||||
# 分割为加密块
|
||||
encrypted_blocks = []
|
||||
for i in range(0, len(encrypted_data), RSACryptoManager.ENCRYPTED_BLOCK_SIZE):
|
||||
block = encrypted_data[i:i + RSACryptoManager.ENCRYPTED_BLOCK_SIZE]
|
||||
encrypted_blocks.append(block)
|
||||
|
||||
# 解密所有块
|
||||
decrypted_blocks = RSACryptoManager.decrypt_blocks(encrypted_blocks, private_key_path)
|
||||
|
||||
# 合并解密后的块
|
||||
return b''.join(decrypted_blocks)
|
||||
|
||||
@staticmethod
|
||||
def encrypt_blocks(blocks, public_key_path):
|
||||
"""
|
||||
批量加密多个数据块
|
||||
|
||||
Args:
|
||||
blocks: 数据块列表
|
||||
public_key_path: 公钥文件路径
|
||||
|
||||
Returns:
|
||||
list: 加密后的数据块列表
|
||||
"""
|
||||
def encrypt_blocks(blocks: List[bytes], public_key_path: str) -> List[bytes]:
|
||||
"""批量加密多个数据块"""
|
||||
public_key = RSACryptoManager.load_public_key(public_key_path)
|
||||
encrypted_blocks = []
|
||||
|
||||
for i, block in enumerate(blocks):
|
||||
try:
|
||||
encrypted_block = RSACrypto.encrypt_block(block, public_key_path)
|
||||
encrypted_block = public_key.encrypt(
|
||||
block,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
encrypted_blocks.append(encrypted_block)
|
||||
except Exception as e:
|
||||
raise ValueError(f"加密第 {i} 个数据块失败: {e}")
|
||||
@@ -138,22 +144,21 @@ class RSACrypto:
|
||||
return encrypted_blocks
|
||||
|
||||
@staticmethod
|
||||
def decrypt_blocks(encrypted_blocks, private_key_path):
|
||||
"""
|
||||
批量解密多个数据块
|
||||
|
||||
Args:
|
||||
encrypted_blocks: 加密的数据块列表
|
||||
private_key_path: 私钥文件路径
|
||||
|
||||
Returns:
|
||||
list: 解密后的原始数据块列表
|
||||
"""
|
||||
def decrypt_blocks(encrypted_blocks: List[bytes], private_key_path: str) -> List[bytes]:
|
||||
"""批量解密多个数据块"""
|
||||
private_key = RSACryptoManager.load_private_key(private_key_path)
|
||||
decrypted_blocks = []
|
||||
|
||||
for i, encrypted_block in enumerate(encrypted_blocks):
|
||||
try:
|
||||
decrypted_block = RSACrypto.decrypt_block(encrypted_block, private_key_path)
|
||||
decrypted_block = private_key.decrypt(
|
||||
encrypted_block,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
decrypted_blocks.append(decrypted_block)
|
||||
except Exception as e:
|
||||
raise ValueError(f"解密第 {i} 个数据块失败: {e}")
|
||||
@@ -161,24 +166,36 @@ class RSACrypto:
|
||||
return decrypted_blocks
|
||||
|
||||
@staticmethod
|
||||
def get_max_block_size():
|
||||
"""
|
||||
获取最大数据块大小
|
||||
|
||||
Returns:
|
||||
int: 最大数据块大小(字节)
|
||||
"""
|
||||
return RSACrypto.MAX_BLOCK_SIZE
|
||||
|
||||
@staticmethod
|
||||
def validate_block_size(block_data):
|
||||
"""
|
||||
验证数据块大小是否合法
|
||||
|
||||
Args:
|
||||
block_data: 数据块
|
||||
def verify_key_pair(private_key_path: str, public_key_path: str) -> bool:
|
||||
"""验证私钥和公钥是否匹配"""
|
||||
try:
|
||||
private_key = RSACryptoManager.load_private_key(private_key_path)
|
||||
public_key = RSACryptoManager.load_public_key(public_key_path)
|
||||
|
||||
Returns:
|
||||
bool: 是否合法
|
||||
"""
|
||||
return len(block_data) <= RSACrypto.MAX_BLOCK_SIZE
|
||||
# 生成测试数据
|
||||
test_data = b"test_data_for_verification"
|
||||
|
||||
# 使用公钥加密
|
||||
encrypted = public_key.encrypt(
|
||||
test_data,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
|
||||
# 使用私钥解密
|
||||
decrypted = private_key.decrypt(
|
||||
encrypted,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
|
||||
return decrypted == test_data
|
||||
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user