Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c8e07610d | ||
|
|
c14cfe14b9 | ||
|
|
1b6add1506 | ||
|
|
67176d865c | ||
|
|
edb6709b4b |
@@ -1,253 +1,3 @@
|
|||||||
# 🌐 TCP IPv6 文件传输工具
|
# TCP-file
|
||||||
|
|
||||||
一个基于TCP IPv6的安全文件传输工具,支持RSA加密传输和友好的交互式界面。
|
基于TPC协议和RSA非对称加密的点对点文件传输软件
|
||||||
|
|
||||||
## ✨ 功能特性
|
|
||||||
|
|
||||||
- ✅ **IPv6 TCP传输** - 原生支持IPv6网络协议
|
|
||||||
- ✅ **RSA加密传输** - 端到端加密保护数据安全
|
|
||||||
- ✅ **交互式Shell** - 美观的命令行界面
|
|
||||||
- ✅ **实时进度显示** - 传输过程可视化
|
|
||||||
- ✅ **跨平台支持** - 支持Windows、Linux、macOS
|
|
||||||
- ✅ **大文件支持** - 自动分块传输大文件
|
|
||||||
- ✅ **密钥管理** - 内置RSA密钥对生成工具
|
|
||||||
|
|
||||||
## 📦 安装要求
|
|
||||||
|
|
||||||
### 系统要求
|
|
||||||
- Python 3.7+
|
|
||||||
- 支持IPv6的网络环境
|
|
||||||
|
|
||||||
### 安装依赖
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### 快速安装
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 克隆项目
|
|
||||||
git clone https://git.23794.top/Alex_jzr/TCP-file.git
|
|
||||||
cd TCP-file
|
|
||||||
|
|
||||||
# 创建虚拟环境
|
|
||||||
python -m venv tcp_venv
|
|
||||||
source tcp_venv/bin/activate # Linux/macOS
|
|
||||||
# 或
|
|
||||||
tcp_venv\Scripts\activate # Windows
|
|
||||||
|
|
||||||
# 安装依赖
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 快速开始
|
|
||||||
|
|
||||||
### 1. 生成RSA密钥对
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 使用内置工具生成密钥对
|
|
||||||
python rsamake.py private_key.pem public_key.pem
|
|
||||||
|
|
||||||
# 或者在Shell中生成
|
|
||||||
python shell.py
|
|
||||||
然后选择选项5生成密钥
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. 启动交互式Shell
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python shell.py
|
|
||||||
```
|
|
||||||
|
|
||||||
您将看到美观的交互式菜单界面:
|
|
||||||
|
|
||||||
```
|
|
||||||
╔══════════════════════════════════════════════════════╗
|
|
||||||
║ ║
|
|
||||||
║🌐 TCP IPv6 文件传输工具 Shell ║
|
|
||||||
║ ║
|
|
||||||
║ 安全 • 高效 • 易用 ║
|
|
||||||
║ ║
|
|
||||||
╚══════════════════════════════════════════════════════╝
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 使用命令行工具
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 发送文件(不加密)
|
|
||||||
python main.py send 文件路径 目标IP 目标端口
|
|
||||||
|
|
||||||
# 发送文件(加密)
|
|
||||||
python main.py send 文件路径 目标IP 目标端口 --encrypt --public-key 公钥路径
|
|
||||||
|
|
||||||
# 接收文件(不加密)
|
|
||||||
python main.py receive 监听端口 输出路径
|
|
||||||
|
|
||||||
# 接收文件(解密)
|
|
||||||
python main.py receive 监听端口 输出路径 --decrypt --private-key 私钥路径
|
|
||||||
|
|
||||||
# 生成密钥对
|
|
||||||
python main.py genkey --private 私钥路径 --public 公钥路径
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📖 详细使用指南
|
|
||||||
|
|
||||||
### 发送文件示例
|
|
||||||
|
|
||||||
#### 不加密传输
|
|
||||||
```bash
|
|
||||||
# 发送文件到本地IPv6地址
|
|
||||||
python main.py send test.txt ::1 3141
|
|
||||||
|
|
||||||
# 发送文件到远程IPv6地址
|
|
||||||
python main.py send document.pdf 2001:db8::1 3141
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 加密传输
|
|
||||||
```bash
|
|
||||||
# 使用加密传输
|
|
||||||
python main.py send secret_file.txt ::1 3141 --encrypt --public-key public_key.pem
|
|
||||||
```
|
|
||||||
|
|
||||||
### 接收文件示例
|
|
||||||
|
|
||||||
#### 不加密接收
|
|
||||||
```bash
|
|
||||||
# 在端口3141监听并保存文件
|
|
||||||
python main.py receive 3141 received_file.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 解密接收
|
|
||||||
```bash
|
|
||||||
# 接收并解密文件
|
|
||||||
python main.py receive 3141 decrypted_file.txt --decrypt --private-key private_key.pem
|
|
||||||
```
|
|
||||||
|
|
||||||
### 交互式Shell使用
|
|
||||||
|
|
||||||
启动Shell后,使用数字选择操作:
|
|
||||||
|
|
||||||
```
|
|
||||||
主菜单:
|
|
||||||
1. 发送文件
|
|
||||||
2. 接收文件
|
|
||||||
3. 停止接收器
|
|
||||||
4. 查看状态
|
|
||||||
5. 生成密钥对
|
|
||||||
6. 查看文件信息
|
|
||||||
7. 退出
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🔐 安全特性
|
|
||||||
|
|
||||||
### RSA加密流程
|
|
||||||
1. **密钥生成** - 使用2048位RSA密钥对
|
|
||||||
2. **数据分块** - 自动将文件分割为190字节的块
|
|
||||||
3. **加密传输** - 每个数据块单独加密
|
|
||||||
4. **解密重组** - 接收端解密并重组文件
|
|
||||||
|
|
||||||
### 加密性能
|
|
||||||
- 最大数据块: 190字节 (2048位RSA)
|
|
||||||
- 加密块大小: 256字节
|
|
||||||
- 支持算法: RSA-OAEP with SHA-256
|
|
||||||
|
|
||||||
## 🌍 IPv6配置指南
|
|
||||||
|
|
||||||
### 检查IPv6支持
|
|
||||||
```bash
|
|
||||||
# Linux/macOS
|
|
||||||
ping6 ::1
|
|
||||||
ip -6 addr show
|
|
||||||
|
|
||||||
|
|
||||||
## 🗂️ 项目结构
|
|
||||||
|
|
||||||
```
|
|
||||||
TCP-file/
|
|
||||||
├── src/ # 源代码目录
|
|
||||||
│ ├── file.py # 文件处理模块
|
|
||||||
│ ├── network.py # 网络传输模块
|
|
||||||
│ └── rsa.py # RSA加密模块
|
|
||||||
├── key/ # 密钥目录(示例)
|
|
||||||
│ ├── private_key.pem # 私钥文件
|
|
||||||
│ ├── public_key.pem # 公钥文件
|
|
||||||
│ └── rsamake.py # 密钥生成工具
|
|
||||||
├── main.py # 主命令行工具
|
|
||||||
├── shell.py # 交互式Shell
|
|
||||||
├── requirements.txt # 依赖列表
|
|
||||||
├── .gitignore # Git忽略规则
|
|
||||||
└── README.md # 项目说明
|
|
||||||
```
|
|
||||||
|
|
||||||
## ⚙️ 配置选项
|
|
||||||
|
|
||||||
### 网络配置
|
|
||||||
```python
|
|
||||||
# 在network.py中可调整的参数
|
|
||||||
TIMEOUT = 30 # 超时时间(秒)
|
|
||||||
CHUNK_SIZE = 4096 # 传输块大小(字节)
|
|
||||||
MAX_RETRIES = 3 # 最大重试次数
|
|
||||||
```
|
|
||||||
|
|
||||||
### 加密配置
|
|
||||||
```python
|
|
||||||
# 在rsa.py中可调整的参数
|
|
||||||
KEY_SIZE = 2048 # RSA密钥长度
|
|
||||||
MAX_BLOCK_SIZE = 190 # 最大加密块大小
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🔧 故障排除
|
|
||||||
|
|
||||||
### 常见问题
|
|
||||||
|
|
||||||
1. **连接被拒绝**
|
|
||||||
```bash
|
|
||||||
# 检查目标是否在监听
|
|
||||||
netstat -tuln | grep 3141
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **IPv6不可用**
|
|
||||||
```bash
|
|
||||||
# 启用IPv6
|
|
||||||
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=0
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **权限不足**
|
|
||||||
```bash
|
|
||||||
# 使用sudo或更改端口
|
|
||||||
sudo python main.py receive 80 output.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
4. **加密解密失败**
|
|
||||||
- 确保使用匹配的密钥对
|
|
||||||
- 检查密钥文件权限
|
|
||||||
|
|
||||||
### 调试模式
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 启用详细日志
|
|
||||||
export LOG_LEVEL=DEBUG
|
|
||||||
python main.py send test.txt ::1 3141
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## 📄 许可证
|
|
||||||
|
|
||||||
本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
|
|
||||||
|
|
||||||
## 🙏 致谢
|
|
||||||
|
|
||||||
- [cryptography](https://cryptography.io/) - 提供加密功能支持
|
|
||||||
- Python 社区 - 优秀的网络编程支持
|
|
||||||
|
|
||||||
## 📞 支持与反馈
|
|
||||||
|
|
||||||
如果您遇到问题或有建议:alex12141327@163.com
|
|
||||||
|
|
||||||
1. 查看 [故障排除](#故障排除) 章节
|
|
||||||
2. 提交 [Issue](https://git.23794.top/Alex_jzr/TCP-file/issues)
|
|
||||||
3. 联系维护者: Alex_jzr
|
|
||||||
---
|
|
||||||
|
|
||||||
**享受安全的文件传输体验!** 🎉
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
from cryptography.hazmat.primitives import serialization
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
||||||
from cryptography.hazmat.backends import default_backend
|
|
||||||
|
|
||||||
# 生成私钥
|
|
||||||
private_key = rsa.generate_private_key(
|
|
||||||
public_exponent=65537,
|
|
||||||
key_size=2048,
|
|
||||||
backend=default_backend()
|
|
||||||
)
|
|
||||||
|
|
||||||
# 获取公钥
|
|
||||||
public_key = private_key.public_key()
|
|
||||||
|
|
||||||
# 序列化私钥
|
|
||||||
private_pem = private_key.private_bytes(
|
|
||||||
encoding=serialization.Encoding.PEM,
|
|
||||||
format=serialization.PrivateFormat.PKCS8,
|
|
||||||
encryption_algorithm=serialization.NoEncryption()
|
|
||||||
)
|
|
||||||
|
|
||||||
# 序列化公钥
|
|
||||||
public_pem = public_key.public_bytes(
|
|
||||||
encoding=serialization.Encoding.PEM,
|
|
||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
||||||
)
|
|
||||||
|
|
||||||
# 保存私钥到文件
|
|
||||||
with open('private_key.pem', 'wb') as f:
|
|
||||||
f.write(private_pem)
|
|
||||||
|
|
||||||
# 保存公钥到文件
|
|
||||||
with open('public_key.pem', 'wb') as f:
|
|
||||||
f.write(public_pem)
|
|
||||||
|
|
||||||
print("RSA密钥对生成成功!")
|
|
||||||
print("私钥已保存到: private_key.pem")
|
|
||||||
print("公钥已保存到: public_key.pem")
|
|
||||||
@@ -1,207 +1,585 @@
|
|||||||
import argparse
|
#!/usr/bin/env python3
|
||||||
import os
|
|
||||||
import sys
|
import sys
|
||||||
from typing import Optional, Tuple
|
import os
|
||||||
from src.file import FileHandler
|
import json
|
||||||
from src.network import TCPIPv6Transporter
|
import base64
|
||||||
from src.rsa import RSACryptoManager
|
from typing import Dict, List, Tuple, Any, Optional
|
||||||
import logging
|
|
||||||
|
|
||||||
# 配置日志
|
# 添加src目录到Python路径
|
||||||
logging.basicConfig(
|
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
|
||||||
level=logging.INFO,
|
|
||||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
||||||
handlers=[
|
|
||||||
logging.FileHandler('tcpfile.log'),
|
|
||||||
logging.StreamHandler(sys.stdout)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
class TCPFileManager:
|
from file import File
|
||||||
|
from network import TCPIPv6Transporter
|
||||||
|
from rsa import RSACrypto
|
||||||
|
|
||||||
|
class FileTransferSystem:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.transporter = TCPIPv6Transporter()
|
self.transporter = TCPIPv6Transporter()
|
||||||
self.current_file_handler: Optional[FileHandler] = None
|
self.received_files = {}
|
||||||
|
self.current_status = "ready"
|
||||||
|
self.temp_files = {}
|
||||||
|
|
||||||
def send_file(self, file_path: str, target_ip: str, target_port: int,
|
|
||||||
encrypt: bool = False, public_key_path: Optional[str] = None) -> Tuple[bool, str]:
|
def process_command(self, command: str, args: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""发送文件"""
|
"""处理来自shell的命令"""
|
||||||
try:
|
try:
|
||||||
# 验证文件
|
self.current_status = "processing"
|
||||||
self.current_file_handler = FileHandler(file_path)
|
|
||||||
if not self.current_file_handler.validate_file_exists():
|
|
||||||
return False, f"文件不存在: {file_path}"
|
|
||||||
|
|
||||||
# 读取文件
|
if command == "send_file":
|
||||||
file_data = self.current_file_handler.read_file()
|
return self._send_file_complete(args)
|
||||||
logger.info(f"读取文件成功,大小: {len(file_data)} bytes")
|
elif command == "start_receiver":
|
||||||
|
return self._start_receiver(args)
|
||||||
# 加密处理
|
elif command == "stop_receiver":
|
||||||
if encrypt:
|
return self._stop_receiver(args)
|
||||||
if not public_key_path:
|
elif command == "get_status":
|
||||||
return False, "加密模式需要指定公钥路径"
|
return self._get_status(args)
|
||||||
if not os.path.exists(public_key_path):
|
elif command == "list_received_files":
|
||||||
return False, f"公钥文件不存在: {public_key_path}"
|
return self._list_received_files(args)
|
||||||
|
elif command == "get_received_file":
|
||||||
logger.info("开始加密文件...")
|
return self._get_received_file(args)
|
||||||
try:
|
elif command == "cleanup":
|
||||||
file_data = RSACryptoManager.encrypt_data(file_data, public_key_path)
|
return self._cleanup(args)
|
||||||
logger.info("文件加密完成")
|
|
||||||
except Exception as e:
|
|
||||||
return False, f"加密失败: {e}"
|
|
||||||
|
|
||||||
# 发送数据
|
|
||||||
success, message = self.transporter.send_data(file_data, target_ip, target_port)
|
|
||||||
return success, message
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
error_msg = f"发送文件失败: {e}"
|
|
||||||
logger.error(error_msg)
|
|
||||||
return False, error_msg
|
|
||||||
|
|
||||||
def receive_file(self, listen_port: int, output_path: str,
|
|
||||||
decrypt: bool = False, private_key_path: Optional[str] = None) -> Tuple[bool, str]:
|
|
||||||
"""接收文件"""
|
|
||||||
try:
|
|
||||||
# 设置接收回调
|
|
||||||
def receive_callback(data: bytes, client_addr: Tuple):
|
|
||||||
logger.info(f"接收到 {len(data)} bytes 数据来自 [{client_addr[0]}]:{client_addr[1]}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 解密处理
|
|
||||||
if decrypt:
|
|
||||||
if not private_key_path:
|
|
||||||
logger.error("解密模式需要指定私钥路径")
|
|
||||||
return
|
|
||||||
if not os.path.exists(private_key_path):
|
|
||||||
logger.error(f"私钥文件不存在: {private_key_path}")
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.info("开始解密文件...")
|
|
||||||
try:
|
|
||||||
data = RSACryptoManager.decrypt_data(data, private_key_path)
|
|
||||||
logger.info("文件解密完成")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"解密失败: {e}")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 保存文件
|
|
||||||
handler = FileHandler(output_path)
|
|
||||||
saved_path = handler.save_file(data, output_path)
|
|
||||||
logger.info(f"文件保存成功: {saved_path}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"处理接收数据失败: {e}")
|
|
||||||
|
|
||||||
# 启动服务器
|
|
||||||
success, message = self.transporter.start_server(listen_port, receive_callback)
|
|
||||||
return success, message
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
error_msg = f"接收文件失败: {e}"
|
|
||||||
logger.error(error_msg)
|
|
||||||
return False, error_msg
|
|
||||||
|
|
||||||
def stop_receiving(self, port: Optional[int] = None) -> Tuple[bool, str]:
|
|
||||||
"""停止接收"""
|
|
||||||
try:
|
|
||||||
if port:
|
|
||||||
return self.transporter.stop_server(port)
|
|
||||||
else:
|
else:
|
||||||
return self.transporter.stop_all_servers()
|
return {
|
||||||
except Exception as e:
|
"success": False,
|
||||||
error_msg = f"停止接收失败: {e}"
|
"message": f"未知命令: {command}",
|
||||||
logger.error(error_msg)
|
"data": None
|
||||||
return False, error_msg
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"处理命令时出错: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
self.current_status = "ready"
|
||||||
|
|
||||||
|
def _send_file_complete(self, args: Dict) -> Dict:
|
||||||
|
"""完整的文件发送流程"""
|
||||||
|
file_path = args.get("file_path")
|
||||||
|
target_ip = args.get("target_ip")
|
||||||
|
target_port = args.get("target_port")
|
||||||
|
public_key_path = args.get("public_key_path")
|
||||||
|
chunk_size = args.get("chunk_size", 2048)
|
||||||
|
|
||||||
|
# 验证参数
|
||||||
|
if not all([file_path, target_ip, target_port]):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少必要参数: file_path, target_ip, target_port",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
if not os.path.exists(file_path):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"文件不存在: {file_path}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. 读取文件
|
||||||
|
file_handler = File(file_path, chunk_size)
|
||||||
|
file_data = file_handler.read_file()
|
||||||
|
|
||||||
|
# 2. 如果需要加密
|
||||||
|
if public_key_path and os.path.exists(public_key_path):
|
||||||
|
# 分割文件为适合RSA加密的小块
|
||||||
|
max_block_size = RSACrypto.get_max_block_size()
|
||||||
|
blocks = []
|
||||||
|
for i in range(0, len(file_data), max_block_size):
|
||||||
|
block = file_data[i:i + max_block_size]
|
||||||
|
blocks.append(block)
|
||||||
|
|
||||||
|
# 加密所有块
|
||||||
|
encrypted_blocks = RSACrypto.encrypt_blocks(blocks, public_key_path)
|
||||||
|
# 合并加密后的块
|
||||||
|
file_data = b''.join(encrypted_blocks)
|
||||||
|
encryption_status = "encrypted"
|
||||||
|
else:
|
||||||
|
encryption_status = "not_encrypted"
|
||||||
|
|
||||||
|
# 3. 发送文件
|
||||||
|
success, message = self.transporter.send_file(file_data, target_ip, target_port)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"文件发送成功 ({encryption_status})",
|
||||||
|
"data": {
|
||||||
|
"file_size": len(file_data),
|
||||||
|
"encryption": encryption_status,
|
||||||
|
"target": f"[{target_ip}]:{target_port}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"发送失败: {message}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"发送流程出错: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_received_data(self, data: bytes, client_addr: Tuple):
|
||||||
|
"""处理接收到的数据回调"""
|
||||||
|
try:
|
||||||
|
file_id = f"{client_addr[0]}_{int(time.time())}"
|
||||||
|
|
||||||
|
# 存储接收到的文件数据
|
||||||
|
self.received_files[file_id] = {
|
||||||
|
'data': data,
|
||||||
|
'from': client_addr,
|
||||||
|
'time': time.time(),
|
||||||
|
'size': len(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"接收到文件 {file_id}, 大小: {len(data)} bytes")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"处理接收数据出错: {e}")
|
||||||
|
|
||||||
|
def _start_receiver(self, args: Dict) -> Dict:
|
||||||
|
"""启动接收器"""
|
||||||
|
listen_port = args.get("listen_port")
|
||||||
|
private_key_path = args.get("private_key_path")
|
||||||
|
|
||||||
|
if not listen_port:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: listen_port",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
# 存储私钥路径用于后续解密
|
||||||
|
if private_key_path and os.path.exists(private_key_path):
|
||||||
|
self.temp_files['private_key_path'] = private_key_path
|
||||||
|
|
||||||
|
try:
|
||||||
|
success, message = self.transporter.start_server(listen_port, self._handle_received_data)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"message": message,
|
||||||
|
"data": {
|
||||||
|
"port": listen_port,
|
||||||
|
"encryption_ready": private_key_path is not None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"启动接收器失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _split_file(self, args: Dict) -> Dict:
|
||||||
|
"""分割文件为块"""
|
||||||
|
file_path = args.get("file_path")
|
||||||
|
chunk_size = args.get("chunk_size", 2048)
|
||||||
|
|
||||||
|
if not file_path or not os.path.exists(file_path):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"文件不存在: {file_path}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
file_handler = File(file_path, chunk_size)
|
||||||
|
chunks = file_handler.split_to_chunks()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"文件分割成功,共 {len(chunks)} 个块",
|
||||||
|
"data": {
|
||||||
|
"chunks_count": len(chunks),
|
||||||
|
"chunk_size": chunk_size,
|
||||||
|
"file_size": os.path.getsize(file_path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"分割文件失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _encrypt_blocks(self, args: Dict) -> Dict:
|
||||||
|
"""加密数据块"""
|
||||||
|
blocks = args.get("blocks")
|
||||||
|
public_key_path = args.get("public_key_path")
|
||||||
|
|
||||||
|
if not blocks or not public_key_path:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: blocks 或 public_key_path",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
if not os.path.exists(public_key_path):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"公钥文件不存在: {public_key_path}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
encrypted_blocks = RSACrypto.encrypt_blocks(blocks, public_key_path)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"加密成功,共 {len(encrypted_blocks)} 个加密块",
|
||||||
|
"data": {
|
||||||
|
"encrypted_blocks": encrypted_blocks,
|
||||||
|
"blocks_count": len(encrypted_blocks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"加密失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _decrypt_blocks(self, args: Dict) -> Dict:
|
||||||
|
"""解密数据块"""
|
||||||
|
encrypted_blocks = args.get("encrypted_blocks")
|
||||||
|
private_key_path = args.get("private_key_path")
|
||||||
|
|
||||||
|
if not encrypted_blocks or not private_key_path:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: encrypted_blocks 或 private_key_path",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
if not os.path.exists(private_key_path):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"私钥文件不存在: {private_key_path}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
decrypted_blocks = RSACrypto.decrypt_blocks(encrypted_blocks, private_key_path)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"解密成功,共 {len(decrypted_blocks)} 个解密块",
|
||||||
|
"data": {
|
||||||
|
"decrypted_blocks": decrypted_blocks,
|
||||||
|
"blocks_count": len(decrypted_blocks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"解密失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _send_file(self, args: Dict) -> Dict:
|
||||||
|
"""发送文件"""
|
||||||
|
file_data = args.get("file_data")
|
||||||
|
target_ip = args.get("target_ip")
|
||||||
|
target_port = args.get("target_port")
|
||||||
|
|
||||||
|
if not file_data or not target_ip or not target_port:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: file_data, target_ip 或 target_port",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
success, message = self.transporter.send_file(file_data, target_ip, target_port)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"message": message,
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"发送文件失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _handle_received_data(self, data: bytes, client_addr: Tuple):
|
||||||
|
"""处理接收到的数据回调"""
|
||||||
|
file_id = f"{client_addr[0]}_{int(time.time())}"
|
||||||
|
self.received_files[file_id] = {
|
||||||
|
'data': data,
|
||||||
|
'from': client_addr,
|
||||||
|
'time': time.time(),
|
||||||
|
'size': len(data)
|
||||||
|
}
|
||||||
|
print(f"接收到文件 {file_id}, 大小: {len(data)} bytes")
|
||||||
|
|
||||||
|
def _start_receiver(self, args: Dict) -> Dict:
|
||||||
|
"""启动接收器"""
|
||||||
|
listen_port = args.get("listen_port")
|
||||||
|
|
||||||
|
if not listen_port:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: listen_port",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
success, message = self.transporter.start_server(listen_port, self._handle_received_data)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"message": message,
|
||||||
|
"data": {
|
||||||
|
"port": listen_port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"启动接收器失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _stop_receiver(self, args: Dict) -> Dict:
|
||||||
|
"""停止接收器"""
|
||||||
|
port = args.get("port")
|
||||||
|
|
||||||
|
if not port:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少参数: port",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
success, message = self.transporter.stop_server(port)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"message": message,
|
||||||
|
"data": {
|
||||||
|
"port": port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"停止接收器失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def _get_status(self, args: Dict) -> Dict:
|
||||||
|
"""获取系统状态"""
|
||||||
|
listening_ports = self.transporter.get_listening_ports()
|
||||||
|
|
||||||
def get_status(self) -> dict:
|
|
||||||
"""获取当前状态"""
|
|
||||||
return {
|
return {
|
||||||
'listening_ports': self.transporter.get_listening_ports(),
|
"success": True,
|
||||||
'current_file': self.current_file_handler.file_path if self.current_file_handler else None
|
"message": "系统状态获取成功",
|
||||||
|
"data": {
|
||||||
|
"status": self.current_status,
|
||||||
|
"listening_ports": listening_ports,
|
||||||
|
"received_files_count": len(self.received_files),
|
||||||
|
"received_files_size": sum(f['size'] for f in self.received_files.values())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def main():
|
def _list_received_files(self, args: Dict) -> Dict:
|
||||||
parser = argparse.ArgumentParser(description="TCP IPv6 文件传输工具")
|
"""列出接收到的文件"""
|
||||||
subparsers = parser.add_subparsers(dest='command', help='命令')
|
files_info = []
|
||||||
|
for file_id, file_data in self.received_files.items():
|
||||||
|
files_info.append({
|
||||||
|
"id": file_id,
|
||||||
|
"size": file_data['size'],
|
||||||
|
"from": file_data['from'],
|
||||||
|
"time": file_data['time']
|
||||||
|
})
|
||||||
|
|
||||||
# 发送文件命令
|
return {
|
||||||
send_parser = subparsers.add_parser('send', help='发送文件')
|
"success": True,
|
||||||
send_parser.add_argument('file', help='要发送的文件路径')
|
"message": f"共 {len(files_info)} 个接收到的文件",
|
||||||
send_parser.add_argument('target_ip', help='目标IPv6地址')
|
"data": {
|
||||||
send_parser.add_argument('target_port', type=int, help='目标端口')
|
"files": files_info
|
||||||
send_parser.add_argument('--encrypt', action='store_true', help='启用加密')
|
}
|
||||||
send_parser.add_argument('--public-key', help='公钥文件路径')
|
}
|
||||||
|
|
||||||
# 接收文件命令
|
def _get_received_file(self, args: Dict) -> Dict:
|
||||||
receive_parser = subparsers.add_parser('receive', help='接收文件')
|
"""获取接收到的文件数据"""
|
||||||
receive_parser.add_argument('port', type=int, help='监听端口')
|
file_id = args.get("file_id")
|
||||||
receive_parser.add_argument('output', help='输出文件路径')
|
|
||||||
receive_parser.add_argument('--decrypt', action='store_true', help='启用解密')
|
|
||||||
receive_parser.add_argument('--private-key', help='私钥文件路径')
|
|
||||||
|
|
||||||
# 停止命令
|
if not file_id or file_id not in self.received_files:
|
||||||
stop_parser = subparsers.add_parser('stop', help='停止接收')
|
return {
|
||||||
stop_parser.add_argument('--port', type=int, help='停止指定端口')
|
"success": False,
|
||||||
|
"message": f"文件不存在: {file_id}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
# 状态命令
|
file_data = self.received_files[file_id]
|
||||||
subparsers.add_parser('status', help='查看状态')
|
|
||||||
|
|
||||||
# 生成密钥命令
|
return {
|
||||||
key_parser = subparsers.add_parser('genkey', help='生成RSA密钥对')
|
"success": True,
|
||||||
key_parser.add_argument('--private', default='private_key.pem', help='私钥输出路径')
|
"message": "文件数据获取成功",
|
||||||
key_parser.add_argument('--public', default='public_key.pem', help='公钥输出路径')
|
"data": {
|
||||||
|
"file_data": file_data['data'],
|
||||||
|
"file_info": {
|
||||||
|
"id": file_id,
|
||||||
|
"size": file_data['size'],
|
||||||
|
"from": file_data['from'],
|
||||||
|
"time": file_data['time']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
args = parser.parse_args()
|
def _get_received_file(self, args: Dict) -> Dict:
|
||||||
|
"""获取接收到的文件数据"""
|
||||||
|
file_id = args.get("file_id")
|
||||||
|
save_path = args.get("save_path")
|
||||||
|
private_key_path = args.get("private_key_path") or self.temp_files.get('private_key_path')
|
||||||
|
|
||||||
manager = TCPFileManager()
|
if not file_id or file_id not in self.received_files:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"文件不存在: {file_id}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if args.command == 'send':
|
file_data = self.received_files[file_id]['data']
|
||||||
success, message = manager.send_file(
|
|
||||||
args.file, args.target_ip, args.target_port,
|
|
||||||
args.encrypt, args.public_key
|
|
||||||
)
|
|
||||||
print(f"{'成功' if success else '失败'}: {message}")
|
|
||||||
|
|
||||||
elif args.command == 'receive':
|
# 尝试解密(如果有私钥)
|
||||||
success, message = manager.receive_file(
|
if private_key_path and os.path.exists(private_key_path):
|
||||||
args.port, args.output,
|
|
||||||
args.decrypt, args.private_key
|
|
||||||
)
|
|
||||||
print(f"{'成功' if success else '失败'}: {message}")
|
|
||||||
if success:
|
|
||||||
print("按 Ctrl+C 停止接收...")
|
|
||||||
try:
|
try:
|
||||||
while True:
|
# RSA加密的数据有固定长度特征
|
||||||
pass
|
if len(file_data) % 256 == 0: # 2048位RSA加密块大小
|
||||||
except KeyboardInterrupt:
|
# 分割为加密块
|
||||||
manager.stop_receiving(args.port)
|
encrypted_blocks = []
|
||||||
print("\n接收已停止")
|
for i in range(0, len(file_data), 256):
|
||||||
|
block = file_data[i:i + 256]
|
||||||
|
encrypted_blocks.append(block)
|
||||||
|
|
||||||
elif args.command == 'stop':
|
# 解密所有块
|
||||||
success, message = manager.stop_receiving(args.port)
|
decrypted_blocks = RSACrypto.decrypt_blocks(encrypted_blocks, private_key_path)
|
||||||
print(f"{'成功' if success else '失败'}: {message}")
|
file_data = b''.join(decrypted_blocks)
|
||||||
|
encryption_status = "decrypted"
|
||||||
|
else:
|
||||||
|
encryption_status = "not_encrypted"
|
||||||
|
except Exception as e:
|
||||||
|
encryption_status = f"decryption_failed: {e}"
|
||||||
|
else:
|
||||||
|
encryption_status = "not_decrypted"
|
||||||
|
|
||||||
elif args.command == 'status':
|
# 保存文件(如果指定了路径)
|
||||||
status = manager.get_status()
|
if save_path:
|
||||||
print("当前状态:")
|
try:
|
||||||
print(f"监听端口: {status['listening_ports']}")
|
file_handler = File(save_path)
|
||||||
print(f"当前文件: {status['current_file']}")
|
file_handler.save_file(file_data)
|
||||||
|
save_status = f"saved_to_{save_path}"
|
||||||
|
except Exception as e:
|
||||||
|
save_status = f"save_failed: {e}"
|
||||||
|
else:
|
||||||
|
save_status = "not_saved"
|
||||||
|
|
||||||
elif args.command == 'genkey':
|
file_info = {
|
||||||
success, message = RSACryptoManager.generate_key_pair(args.private, args.public)
|
"id": file_id,
|
||||||
print(f"{'成功' if success else '失败'}: {message}")
|
"size": len(file_data),
|
||||||
|
"from": self.received_files[file_id]['from'],
|
||||||
|
"time": self.received_files[file_id]['time'],
|
||||||
|
"encryption_status": encryption_status,
|
||||||
|
"save_status": save_status
|
||||||
|
}
|
||||||
|
|
||||||
else:
|
return {
|
||||||
parser.print_help()
|
"success": True,
|
||||||
|
"message": "文件数据获取成功",
|
||||||
|
"data": {
|
||||||
|
"file_data": base64.b64encode(file_data).decode('utf-8') if not save_path else None,
|
||||||
|
"file_info": file_info
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except Exception as e:
|
||||||
print("\n操作被用户中断")
|
return {
|
||||||
sys.exit(0)
|
"success": False,
|
||||||
except Exception as e:
|
"message": f"获取文件失败: {e}",
|
||||||
logger.error(f"程序执行错误: {e}")
|
"data": None
|
||||||
sys.exit(1)
|
}
|
||||||
|
|
||||||
|
def _cleanup(self, args: Dict) -> Dict:
|
||||||
|
"""清理资源"""
|
||||||
|
try:
|
||||||
|
# 停止所有服务器
|
||||||
|
success, message = self.transporter.stop_all_servers()
|
||||||
|
|
||||||
|
# 清空接收文件缓存
|
||||||
|
self.received_files.clear()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"message": f"清理完成: {message}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"清理失败: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""主程序入口"""
|
||||||
|
system = FileTransferSystem()
|
||||||
|
|
||||||
|
# 从标准输入读取命令
|
||||||
|
for line in sys.stdin:
|
||||||
|
try:
|
||||||
|
# 解析JSON命令
|
||||||
|
command_data = json.loads(line.strip())
|
||||||
|
command = command_data.get("command")
|
||||||
|
args = command_data.get("args", {})
|
||||||
|
|
||||||
|
if not command:
|
||||||
|
result = {
|
||||||
|
"success": False,
|
||||||
|
"message": "缺少命令名称",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 处理命令
|
||||||
|
result = system.process_command(command, args)
|
||||||
|
|
||||||
|
# 输出结果
|
||||||
|
print(json.dumps(result))
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
result = {
|
||||||
|
"success": False,
|
||||||
|
"message": "无效的JSON格式",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
print(json.dumps(result))
|
||||||
|
sys.stdout.flush()
|
||||||
|
except Exception as e:
|
||||||
|
result = {
|
||||||
|
"success": False,
|
||||||
|
"message": f"处理命令时发生错误: {e}",
|
||||||
|
"data": None
|
||||||
|
}
|
||||||
|
print(json.dumps(result))
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
@@ -1,417 +1,218 @@
|
|||||||
import cmd
|
#!/usr/bin/env python3
|
||||||
import os
|
import json
|
||||||
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import os
|
||||||
import time
|
import time
|
||||||
from typing import List, Optional, Tuple
|
import base64
|
||||||
from src.file import FileHandler
|
from typing import Dict, Any, List
|
||||||
from src.network import TCPIPv6Transporter
|
import argparse
|
||||||
from src.rsa import RSACryptoManager
|
import readline
|
||||||
import logging
|
|
||||||
import threading
|
|
||||||
from enum import Enum
|
|
||||||
|
|
||||||
# 配置日志
|
|
||||||
logging.basicConfig(
|
|
||||||
level=logging.INFO,
|
|
||||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
|
||||||
)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
class Color:
|
|
||||||
"""颜色定义"""
|
|
||||||
GREEN = '\033[92m'
|
|
||||||
BLUE = '\033[94m'
|
|
||||||
YELLOW = '\033[93m'
|
|
||||||
RED = '\033[91m'
|
|
||||||
PURPLE = '\033[95m'
|
|
||||||
CYAN = '\033[96m'
|
|
||||||
BOLD = '\033[1m'
|
|
||||||
UNDERLINE = '\033[4m'
|
|
||||||
END = '\033[0m'
|
|
||||||
|
|
||||||
class MenuOption(Enum):
|
|
||||||
"""菜单选项"""
|
|
||||||
SEND_FILE = 1
|
|
||||||
RECEIVE_FILE = 2
|
|
||||||
STOP_RECEIVER = 3
|
|
||||||
STATUS = 4
|
|
||||||
GENERATE_KEYS = 5
|
|
||||||
FILE_INFO = 6
|
|
||||||
EXIT = 7
|
|
||||||
|
|
||||||
class TCPFileShell(cmd.Cmd):
|
|
||||||
intro = f"""
|
|
||||||
{Color.BOLD}{Color.CYAN}╔══════════════════════════════════════════════════════╗
|
|
||||||
║{'':^54}║
|
|
||||||
║{Color.GREEN}🌐 TCP IPv6 文件传输工具 Shell{Color.CYAN}{'':24}║
|
|
||||||
║{'':^54}║
|
|
||||||
║{Color.YELLOW} 安全 • 高效 • 易用{Color.CYAN}{'':28}║
|
|
||||||
║{'':^54}║
|
|
||||||
╚══════════════════════════════════════════════════════╝{Color.END}
|
|
||||||
|
|
||||||
{Color.BLUE}请输入数字选择操作:{Color.END}
|
|
||||||
"""
|
|
||||||
prompt = f'{Color.BOLD}{Color.GREEN}tcpfile>{Color.END} '
|
|
||||||
|
|
||||||
|
class FileTransferShell:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
self.process = None
|
||||||
self.transporter = TCPIPv6Transporter()
|
self.start_main_process()
|
||||||
self.current_file: Optional[str] = None
|
|
||||||
self.current_file_handler: Optional[FileHandler] = None
|
|
||||||
self.use_rich_display = self._check_rich_available()
|
|
||||||
|
|
||||||
def _check_rich_available(self):
|
def start_main_process(self):
|
||||||
"""检查是否可用rich库"""
|
"""启动主程序进程"""
|
||||||
try:
|
try:
|
||||||
import rich
|
self.process = subprocess.Popen(
|
||||||
return True
|
[sys.executable, "main.py"],
|
||||||
except ImportError:
|
stdin=subprocess.PIPE,
|
||||||
return False
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
bufsize=1
|
||||||
|
)
|
||||||
|
print("✓ 文件传输系统已启动")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ 启动失败: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
def _print_header(self, title: str):
|
def send_command(self, command: str, args: Dict[str, Any] = None) -> Dict[str, Any]:
|
||||||
"""打印标题"""
|
"""发送命令到主程序"""
|
||||||
print(f"\n{Color.BOLD}{Color.CYAN}╔{'═' * 60}╗")
|
if args is None:
|
||||||
print(f"║ {Color.GREEN}{title:<59}{Color.CYAN}║")
|
args = {}
|
||||||
print(f"╚{'═' * 60}╝{Color.END}\n")
|
|
||||||
|
|
||||||
def _print_success(self, message: str):
|
|
||||||
"""打印成功信息"""
|
|
||||||
print(f"{Color.GREEN}✓ {message}{Color.END}")
|
|
||||||
|
|
||||||
def _print_error(self, message: str):
|
|
||||||
"""打印错误信息"""
|
|
||||||
print(f"{Color.RED}✗ {message}{Color.END}")
|
|
||||||
|
|
||||||
def _print_warning(self, message: str):
|
|
||||||
"""打印警告信息"""
|
|
||||||
print(f"{Color.YELLOW}⚠ {message}{Color.END}")
|
|
||||||
|
|
||||||
def _print_info(self, message: str):
|
|
||||||
"""打印信息"""
|
|
||||||
print(f"{Color.BLUE}ℹ {message}{Color.END}")
|
|
||||||
|
|
||||||
def _print_progress(self, current: int, total: int, prefix: str = ""):
|
|
||||||
"""打印进度条"""
|
|
||||||
percent = (current / total) * 100
|
|
||||||
bar_length = 30
|
|
||||||
filled_length = int(bar_length * current // total)
|
|
||||||
bar = f"{Color.GREEN}{'█' * filled_length}{Color.YELLOW}{'░' * (bar_length - filled_length)}{Color.END}"
|
|
||||||
print(f"\r{prefix} {bar} {percent:.1f}% ({current}/{total})", end='', flush=True)
|
|
||||||
if current == total:
|
|
||||||
print()
|
|
||||||
|
|
||||||
def _input_with_prompt(self, prompt: str, default: str = "") -> str:
|
|
||||||
"""带提示的输入"""
|
|
||||||
return input(f"{Color.BOLD}{Color.CYAN}{prompt}{Color.END} ").strip() or default
|
|
||||||
|
|
||||||
def _wait_for_seconds(self, seconds: int, message: str = "等待中"):
|
|
||||||
"""等待指定秒数"""
|
|
||||||
for i in range(seconds, 0, -1):
|
|
||||||
print(f"\r{message} {i}秒...", end='', flush=True)
|
|
||||||
time.sleep(1)
|
|
||||||
print("\r" + " " * 50 + "\r", end='', flush=True)
|
|
||||||
|
|
||||||
def _show_main_menu(self):
|
|
||||||
"""显示主菜单"""
|
|
||||||
print(f"\n{Color.BOLD}{Color.PURPLE}主菜单:{Color.END}")
|
|
||||||
print(f"{Color.CYAN}1.{Color.END} 发送文件")
|
|
||||||
print(f"{Color.CYAN}2.{Color.END} 接收文件")
|
|
||||||
print(f"{Color.CYAN}3.{Color.END} 停止接收器")
|
|
||||||
print(f"{Color.CYAN}4.{Color.END} 查看状态")
|
|
||||||
print(f"{Color.CYAN}5.{Color.END} 生成密钥对")
|
|
||||||
print(f"{Color.CYAN}6.{Color.END} 查看文件信息")
|
|
||||||
print(f"{Color.CYAN}7.{Color.END} 退出")
|
|
||||||
print(f"{Color.YELLOW}{'─' * 40}{Color.END}")
|
|
||||||
|
|
||||||
def _get_menu_choice(self) -> Optional[MenuOption]:
|
|
||||||
"""获取菜单选择"""
|
|
||||||
try:
|
try:
|
||||||
choice = self._input_with_prompt("请选择操作 (1-7):")
|
command_data = {
|
||||||
return MenuOption(int(choice))
|
"command": command,
|
||||||
except (ValueError, TypeError):
|
"args": args
|
||||||
self._print_error("无效的选择,请输入1-7的数字")
|
}
|
||||||
return None
|
|
||||||
|
|
||||||
def _send_file_interactive(self):
|
self.process.stdin.write(json.dumps(command_data) + '\n')
|
||||||
"""交互式发送文件"""
|
self.process.stdin.flush()
|
||||||
self._print_header("📤 发送文件")
|
|
||||||
|
response_line = self.process.stdout.readline().strip()
|
||||||
|
if not response_line:
|
||||||
|
return {"success": False, "message": "无响应", "data": None}
|
||||||
|
|
||||||
|
return json.loads(response_line)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {"success": False, "message": f"通信错误: {e}", "data": None}
|
||||||
|
|
||||||
|
def print_result(self, result: Dict[str, Any]):
|
||||||
|
"""美化打印结果"""
|
||||||
|
if result["success"]:
|
||||||
|
print(f"✓ {result['message']}")
|
||||||
|
if result["data"]:
|
||||||
|
print("数据详情:")
|
||||||
|
print(json.dumps(result["data"], indent=2, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
print(f"✗ {result['message']}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
def send_file_interactive(self):
|
||||||
|
"""交互式文件发送"""
|
||||||
|
print("\n=== 文件发送模式 ===")
|
||||||
|
|
||||||
# 获取文件路径
|
# 获取文件路径
|
||||||
file_path = self._input_with_prompt("请输入要发送的文件路径:")
|
file_path = input("请输入要发送的文件路径: ").strip()
|
||||||
if not file_path or not os.path.exists(file_path):
|
if not os.path.exists(file_path):
|
||||||
self._print_error("文件不存在或路径无效")
|
print("文件不存在!")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 获取目标地址
|
# 获取目标地址
|
||||||
target_ip = self._input_with_prompt("请输入目标IPv6地址:", "::1")
|
target_ip = input("请输入目标IPv6地址: ").strip()
|
||||||
target_port = self._input_with_prompt("请输入目标端口:", "3141")
|
target_port = int(input("请输入目标端口: ").strip())
|
||||||
|
|
||||||
try:
|
|
||||||
target_port = int(target_port)
|
|
||||||
except ValueError:
|
|
||||||
self._print_error("端口必须是数字")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 询问是否加密
|
# 询问是否加密
|
||||||
use_encryption = self._input_with_prompt("是否使用加密? (y/n):", "n").lower() == 'y'
|
use_encryption = input("是否使用加密?(y/n): ").strip().lower() == 'y'
|
||||||
public_key_path = None
|
public_key_path = None
|
||||||
|
|
||||||
if use_encryption:
|
if use_encryption:
|
||||||
public_key_path = self._input_with_prompt("请输入公钥文件路径:")
|
public_key_path = input("请输入公钥文件路径: ").strip()
|
||||||
if not public_key_path or not os.path.exists(public_key_path):
|
if not os.path.exists(public_key_path):
|
||||||
self._print_error("公钥文件不存在")
|
print("公钥文件不存在!")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 确认发送
|
|
||||||
print(f"\n{Color.YELLOW}发送配置:{Color.END}")
|
|
||||||
print(f"文件: {file_path}")
|
|
||||||
print(f"目标: [{target_ip}]:{target_port}")
|
|
||||||
print(f"加密: {'是' if use_encryption else '否'}")
|
|
||||||
|
|
||||||
confirm = self._input_with_prompt("确认发送? (y/n):", "y").lower()
|
|
||||||
if confirm != 'y':
|
|
||||||
self._print_info("发送已取消")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 发送文件
|
# 发送文件
|
||||||
try:
|
args = {
|
||||||
self.current_file_handler = FileHandler(file_path)
|
"file_path": file_path,
|
||||||
file_data = self.current_file_handler.read_file()
|
"target_ip": target_ip,
|
||||||
self._print_success(f"读取文件成功,大小: {len(file_data)} bytes")
|
"target_port": target_port
|
||||||
|
}
|
||||||
|
|
||||||
if use_encryption and public_key_path:
|
if public_key_path:
|
||||||
self._print_info("开始加密文件...")
|
args["public_key_path"] = public_key_path
|
||||||
file_data = RSACryptoManager.encrypt_data(file_data, public_key_path)
|
|
||||||
self._print_success("文件加密完成")
|
|
||||||
|
|
||||||
self._print_info("正在连接目标服务器...")
|
result = self.send_command("send_file", args)
|
||||||
self._wait_for_seconds(3, "连接中")
|
self.print_result(result)
|
||||||
|
|
||||||
success, message = self.transporter.send_data(file_data, target_ip, target_port)
|
def receive_file_interactive(self):
|
||||||
|
"""交互式文件接收"""
|
||||||
if success:
|
print("\n=== 文件接收模式 ===")
|
||||||
self._print_success(f"文件发送成功: {message}")
|
|
||||||
else:
|
|
||||||
self._print_error(f"发送失败: {message}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self._print_error(f"发送文件失败: {e}")
|
|
||||||
|
|
||||||
def _receive_file_interactive(self):
|
|
||||||
"""交互式接收文件"""
|
|
||||||
self._print_header("📥 接收文件")
|
|
||||||
|
|
||||||
# 获取监听端口
|
# 获取监听端口
|
||||||
port = self._input_with_prompt("请输入监听端口:", "3141")
|
listen_port = int(input("请输入监听端口: ").strip())
|
||||||
try:
|
|
||||||
port = int(port)
|
|
||||||
except ValueError:
|
|
||||||
self._print_error("端口必须是数字")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 获取输出路径
|
# 询问是否有私钥
|
||||||
output_path = self._input_with_prompt("请输入文件保存路径:", f"received_file_{int(time.time())}")
|
use_decryption = input("是否准备解密文件?(y/n): ").strip().lower() == 'y'
|
||||||
|
|
||||||
# 询问是否解密
|
|
||||||
use_decryption = self._input_with_prompt("是否准备解密文件? (y/n):", "n").lower() == 'y'
|
|
||||||
private_key_path = None
|
private_key_path = None
|
||||||
|
|
||||||
if use_decryption:
|
if use_decryption:
|
||||||
private_key_path = self._input_with_prompt("请输入私钥文件路径:")
|
private_key_path = input("请输入私钥文件路径: ").strip()
|
||||||
if not private_key_path or not os.path.exists(private_key_path):
|
if not os.path.exists(private_key_path):
|
||||||
self._print_error("私钥文件不存在")
|
print("私钥文件不存在!")
|
||||||
return
|
return
|
||||||
|
|
||||||
def receive_callback(data: bytes, client_addr: Tuple):
|
|
||||||
client_ip, client_port = client_addr[0], client_addr[1]
|
|
||||||
self._print_success(f"接收到 {len(data)} bytes 数据来自 [{client_ip}]:{client_port}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
if use_decryption and private_key_path:
|
|
||||||
self._print_info("开始解密文件...")
|
|
||||||
data = RSACryptoManager.decrypt_data(data, private_key_path)
|
|
||||||
self._print_success("文件解密完成")
|
|
||||||
|
|
||||||
handler = FileHandler(output_path)
|
|
||||||
saved_path = handler.save_file(data, output_path)
|
|
||||||
self._print_success(f"文件保存成功: {saved_path}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self._print_error(f"处理接收数据失败: {e}")
|
|
||||||
|
|
||||||
# 启动接收器
|
# 启动接收器
|
||||||
success, message = self.transporter.start_server(port, receive_callback)
|
args = {"listen_port": listen_port}
|
||||||
|
if private_key_path:
|
||||||
|
args["private_key_path"] = private_key_path
|
||||||
|
|
||||||
if success:
|
result = self.send_command("start_receiver", args)
|
||||||
self._print_success(f"接收器启动成功: {message}")
|
self.print_result(result)
|
||||||
print(f"\n{Color.YELLOW}接收器正在端口 {port} 监听...{Color.END}")
|
|
||||||
print(f"{Color.CYAN}按 Ctrl+C 返回主菜单停止接收{Color.END}")
|
|
||||||
|
|
||||||
try:
|
if result["success"]:
|
||||||
while True:
|
print(f"接收器已在端口 {listen_port} 启动,等待文件传输...")
|
||||||
time.sleep(1)
|
print("输入 'stop' 停止接收器")
|
||||||
except KeyboardInterrupt:
|
|
||||||
self.transporter.stop_server(port)
|
|
||||||
self._print_info("接收已停止")
|
|
||||||
else:
|
|
||||||
self._print_error(f"启动接收器失败: {message}")
|
|
||||||
|
|
||||||
def _stop_receiver_interactive(self):
|
def stop_receiver_interactive(self):
|
||||||
"""交互式停止接收器"""
|
"""停止接收器"""
|
||||||
self._print_header("⏹️ 停止接收器")
|
port = int(input("请输入要停止的端口: ").strip())
|
||||||
|
result = self.send_command("stop_receiver", {"port": port})
|
||||||
|
self.print_result(result)
|
||||||
|
|
||||||
ports = self.transporter.get_listening_ports()
|
def list_received_files(self):
|
||||||
if not ports:
|
"""列出接收到的文件"""
|
||||||
self._print_info("当前没有运行的接收器")
|
result = self.send_command("list_received_files", {})
|
||||||
return
|
self.print_result(result)
|
||||||
|
|
||||||
print(f"{Color.YELLOW}当前运行的接收器端口: {ports}{Color.END}")
|
def save_received_file(self):
|
||||||
|
"""保存接收到的文件"""
|
||||||
|
file_id = input("请输入文件ID: ").strip()
|
||||||
|
save_path = input("请输入保存路径: ").strip()
|
||||||
|
|
||||||
port_input = self._input_with_prompt("请输入要停止的端口 (留空停止所有):")
|
# 检查是否有私钥
|
||||||
port = None
|
private_key_path = None
|
||||||
|
use_decryption = input("是否使用私钥解密?(y/n): ").strip().lower() == 'y'
|
||||||
if port_input:
|
if use_decryption:
|
||||||
try:
|
private_key_path = input("请输入私钥文件路径: ").strip()
|
||||||
port = int(port_input)
|
if not os.path.exists(private_key_path):
|
||||||
except ValueError:
|
print("私钥文件不存在!")
|
||||||
self._print_error("端口必须是数字")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
success, message = self.transporter.stop_server(port) if port else self.transporter.stop_all_servers()
|
args = {"file_id": file_id, "save_path": save_path}
|
||||||
|
if private_key_path:
|
||||||
|
args["private_key_path"] = private_key_path
|
||||||
|
|
||||||
if success:
|
result = self.send_command("get_received_file", args)
|
||||||
self._print_success(message)
|
self.print_result(result)
|
||||||
else:
|
|
||||||
self._print_error(message)
|
|
||||||
|
|
||||||
def _show_status(self):
|
def interactive_shell(self):
|
||||||
"""显示状态"""
|
"""交互式Shell"""
|
||||||
self._print_header("📊 系统状态")
|
print("=" * 60)
|
||||||
|
print(" 文件传输系统 - 简化模式")
|
||||||
|
print("=" * 60)
|
||||||
|
print("可用命令:")
|
||||||
|
print(" send - 发送文件")
|
||||||
|
print(" receive - 启动接收器")
|
||||||
|
print(" stop - 停止接收器")
|
||||||
|
print(" list - 列出接收的文件")
|
||||||
|
print(" save - 保存接收的文件")
|
||||||
|
print(" status - 查看系统状态")
|
||||||
|
print(" cleanup - 清理资源")
|
||||||
|
print(" exit - 退出程序")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
ports = self.transporter.get_listening_ports()
|
while True:
|
||||||
print(f"{Color.CYAN}监听端口:{Color.END} {ports if ports else '无'}")
|
|
||||||
print(f"{Color.CYAN}当前文件:{Color.END} {self.current_file or '无'}")
|
|
||||||
|
|
||||||
if ports:
|
|
||||||
self._print_info("有接收器正在运行中")
|
|
||||||
else:
|
|
||||||
self._print_info("系统空闲")
|
|
||||||
|
|
||||||
def _generate_keys_interactive(self):
|
|
||||||
"""交互式生成密钥对"""
|
|
||||||
self._print_header("🔑 生成RSA密钥对")
|
|
||||||
|
|
||||||
private_path = self._input_with_prompt("私钥保存路径:", "private_key.pem")
|
|
||||||
public_path = self._input_with_prompt("公钥保存路径:", "public_key.pem")
|
|
||||||
|
|
||||||
# 检查目录是否存在
|
|
||||||
for path in [private_path, public_path]:
|
|
||||||
dir_path = os.path.dirname(path)
|
|
||||||
if dir_path and not os.path.exists(dir_path):
|
|
||||||
os.makedirs(dir_path, exist_ok=True)
|
|
||||||
|
|
||||||
success, message = RSACryptoManager.generate_key_pair(private_path, public_path)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
self._print_success(message)
|
|
||||||
# 验证密钥对
|
|
||||||
if RSACryptoManager.verify_key_pair(private_path, public_path):
|
|
||||||
self._print_success("密钥对验证成功")
|
|
||||||
else:
|
|
||||||
self._print_warning("密钥对验证失败")
|
|
||||||
else:
|
|
||||||
self._print_error(message)
|
|
||||||
|
|
||||||
def _show_file_info(self):
|
|
||||||
"""显示文件信息"""
|
|
||||||
self._print_header("📄 文件信息")
|
|
||||||
|
|
||||||
file_path = self._input_with_prompt("请输入文件路径:")
|
|
||||||
if not file_path or not os.path.exists(file_path):
|
|
||||||
self._print_error("文件不存在")
|
|
||||||
return
|
|
||||||
|
|
||||||
handler = FileHandler(file_path)
|
|
||||||
info = handler.get_file_info()
|
|
||||||
|
|
||||||
if info:
|
|
||||||
print(f"\n{Color.GREEN}文件信息:{Color.END}")
|
|
||||||
print(f"{Color.CYAN}路径:{Color.END} {info['path']}")
|
|
||||||
print(f"{Color.CYAN}大小:{Color.END} {info['size']} bytes")
|
|
||||||
print(f"{Color.CYAN}SHA256:{Color.END} {info['hash']}")
|
|
||||||
print(f"{Color.CYAN}分块数:{Color.END} {info['chunks_count']}")
|
|
||||||
print(f"{Color.CYAN}块大小:{Color.END} {info['chunk_size']} bytes")
|
|
||||||
else:
|
|
||||||
self._print_error("获取文件信息失败")
|
|
||||||
|
|
||||||
def default(self, line):
|
|
||||||
"""处理数字菜单选择"""
|
|
||||||
if line.strip().isdigit():
|
|
||||||
choice = int(line.strip())
|
|
||||||
try:
|
try:
|
||||||
menu_option = MenuOption(choice)
|
command = input("ftp> ").strip().lower()
|
||||||
self._handle_menu_choice(menu_option)
|
|
||||||
except ValueError:
|
|
||||||
self._print_error("无效的选择,请输入1-7的数字")
|
|
||||||
else:
|
|
||||||
print(f"{Color.RED}未知命令: {line}{Color.END}")
|
|
||||||
print(f"请输入1-7的数字选择菜单选项")
|
|
||||||
|
|
||||||
def _handle_menu_choice(self, choice: MenuOption):
|
if command == "exit":
|
||||||
"""处理菜单选择"""
|
print("再见!")
|
||||||
if choice == MenuOption.SEND_FILE:
|
break
|
||||||
self._send_file_interactive()
|
elif command == "send":
|
||||||
elif choice == MenuOption.RECEIVE_FILE:
|
self.send_file_interactive()
|
||||||
self._receive_file_interactive()
|
elif command == "receive":
|
||||||
elif choice == MenuOption.STOP_RECEIVER:
|
self.receive_file_interactive()
|
||||||
self._stop_receiver_interactive()
|
elif command == "stop":
|
||||||
elif choice == MenuOption.STATUS:
|
self.stop_receiver_interactive()
|
||||||
self._show_status()
|
elif command == "list":
|
||||||
elif choice == MenuOption.GENERATE_KEYS:
|
self.list_received_files()
|
||||||
self._generate_keys_interactive()
|
elif command == "save":
|
||||||
elif choice == MenuOption.FILE_INFO:
|
self.save_received_file()
|
||||||
self._show_file_info()
|
elif command == "status":
|
||||||
elif choice == MenuOption.EXIT:
|
result = self.send_command("get_status", {})
|
||||||
return self.do_exit("")
|
self.print_result(result)
|
||||||
|
elif command == "cleanup":
|
||||||
|
result = self.send_command("cleanup", {})
|
||||||
|
self.print_result(result)
|
||||||
|
elif command == "":
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
print("未知命令,可用命令: send, receive, stop, list, save, status, cleanup, exit")
|
||||||
|
|
||||||
# 返回主菜单
|
except KeyboardInterrupt:
|
||||||
input(f"\n{Color.YELLOW}按回车键返回主菜单...{Color.END}")
|
print("\n输入 'exit' 退出程序")
|
||||||
self._show_main_menu()
|
except Exception as e:
|
||||||
|
print(f"错误: {e}")
|
||||||
def do_exit(self, _):
|
|
||||||
"""退出程序"""
|
|
||||||
print(f"\n{Color.CYAN}正在清理资源...{Color.END}")
|
|
||||||
self.transporter.stop_all_servers()
|
|
||||||
print(f"{Color.GREEN}再见!{Color.END}")
|
|
||||||
return True
|
|
||||||
|
|
||||||
def do_quit(self, _):
|
|
||||||
"""退出程序"""
|
|
||||||
return self.do_exit(_)
|
|
||||||
|
|
||||||
def do_EOF(self, _):
|
|
||||||
"""退出程序 (Ctrl+D)"""
|
|
||||||
print()
|
|
||||||
return self.do_exit(_)
|
|
||||||
|
|
||||||
def preloop(self):
|
|
||||||
"""程序开始前执行"""
|
|
||||||
print(self.intro)
|
|
||||||
self._show_main_menu()
|
|
||||||
|
|
||||||
def postloop(self):
|
|
||||||
"""程序结束后执行"""
|
|
||||||
print(f"{Color.CYAN}谢谢使用!{Color.END}")
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
try:
|
"""Shell主入口"""
|
||||||
shell = TCPFileShell()
|
shell = FileTransferShell()
|
||||||
shell.cmdloop()
|
shell.interactive_shell()
|
||||||
except KeyboardInterrupt:
|
|
||||||
print(f"\n{Color.YELLOW}程序被用户中断{Color.END}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"程序执行错误: {e}")
|
|
||||||
print(f"{Color.RED}程序发生错误: {e}{Color.END}")
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
+39
-70
@@ -1,93 +1,62 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import hashlib
|
import hashlib
|
||||||
from typing import List, Dict, Any, Optional
|
|
||||||
|
|
||||||
class FileHandler:
|
class File:
|
||||||
def __init__(self, file_path: str, chunk_size: int = 2048):
|
def __init__(self, file_path, chunk_size=2048):
|
||||||
self.file_path = file_path
|
self.file_path = file_path
|
||||||
self.chunk_size = chunk_size
|
self.chunk_size = chunk_size
|
||||||
|
|
||||||
def validate_file_exists(self) -> bool:
|
def split_to_chunks(self):
|
||||||
"""验证文件是否存在"""
|
|
||||||
return os.path.exists(self.file_path)
|
|
||||||
|
|
||||||
def split_to_chunks(self) -> List[bytes]:
|
|
||||||
"""将文件分割为指定大小的块"""
|
"""将文件分割为指定大小的块"""
|
||||||
if not self.validate_file_exists():
|
|
||||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
|
||||||
|
|
||||||
chunks = []
|
chunks = []
|
||||||
try:
|
with open(self.file_path, 'rb') as f:
|
||||||
with open(self.file_path, 'rb') as f:
|
while True:
|
||||||
while True:
|
chunk = f.read(self.chunk_size)
|
||||||
chunk = f.read(self.chunk_size)
|
if not chunk:
|
||||||
if not chunk:
|
break
|
||||||
break
|
chunks.append(chunk)
|
||||||
chunks.append(chunk)
|
return chunks
|
||||||
return chunks
|
|
||||||
except IOError as e:
|
|
||||||
raise IOError(f"读取文件失败: {e}")
|
|
||||||
|
|
||||||
def read_file(self) -> bytes:
|
def read_file(self):
|
||||||
"""读取整个文件为二进制数据"""
|
"""读取整个文件为二进制数据"""
|
||||||
if not self.validate_file_exists():
|
with open(self.file_path, 'rb') as f:
|
||||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
return f.read()
|
||||||
|
|
||||||
try:
|
def save_file(self, data, output_path=None):
|
||||||
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
|
if output_path is None:
|
||||||
|
output_path = self.file_path
|
||||||
|
|
||||||
try:
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
with open(output_path, 'wb') as f:
|
||||||
with open(save_path, 'wb') as f:
|
f.write(data)
|
||||||
f.write(data)
|
return output_path
|
||||||
return save_path
|
|
||||||
except IOError as e:
|
|
||||||
raise IOError(f"保存文件失败: {e}")
|
|
||||||
|
|
||||||
def get_file_info(self) -> Optional[Dict[str, Any]]:
|
def get_file_info(self):
|
||||||
"""获取文件信息"""
|
"""获取文件信息"""
|
||||||
if not self.validate_file_exists():
|
if not os.path.exists(self.file_path):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
file_size = os.path.getsize(self.file_path)
|
||||||
file_size = os.path.getsize(self.file_path)
|
file_hash = self.calculate_hash()
|
||||||
file_hash = self.calculate_hash()
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'path': self.file_path,
|
'path': self.file_path,
|
||||||
'size': file_size,
|
'size': file_size,
|
||||||
'hash': file_hash,
|
'hash': file_hash,
|
||||||
'chunks_count': (file_size + self.chunk_size - 1) // self.chunk_size,
|
'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, algorithm: str = 'sha256') -> str:
|
def calculate_hash(self):
|
||||||
"""计算文件哈希值"""
|
"""计算文件SHA256哈希值"""
|
||||||
if not self.validate_file_exists():
|
sha256_hash = hashlib.sha256()
|
||||||
raise FileNotFoundError(f"文件不存在: {self.file_path}")
|
with open(self.file_path, "rb") as f:
|
||||||
|
for byte_block in iter(lambda: f.read(4096), b""):
|
||||||
hash_func = getattr(hashlib, algorithm)()
|
sha256_hash.update(byte_block)
|
||||||
|
return sha256_hash.hexdigest()
|
||||||
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
|
@staticmethod
|
||||||
def combine_chunks(chunks: List[bytes]) -> bytes:
|
def combine_chunks(chunks):
|
||||||
"""合并数据块为完整文件"""
|
"""合并数据块为完整文件"""
|
||||||
if not chunks:
|
|
||||||
raise ValueError("数据块列表为空")
|
|
||||||
return b''.join(chunks)
|
return b''.join(chunks)
|
||||||
|
|||||||
+141
-136
@@ -1,119 +1,125 @@
|
|||||||
|
|
||||||
import socket
|
import socket
|
||||||
import threading
|
import threading
|
||||||
import struct
|
import struct
|
||||||
import time
|
import time
|
||||||
from typing import Callable, Optional, Tuple, Dict, List
|
from typing import Callable, Optional, Tuple
|
||||||
import logging
|
|
||||||
|
|
||||||
# 配置日志
|
|
||||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
class TCPIPv6Transporter:
|
class TCPIPv6Transporter:
|
||||||
def __init__(self, timeout: int = 30, chunk_size: int = 4096):
|
def __init__(self):
|
||||||
self.servers: Dict[int, socket.socket] = {}
|
self.servers = {} # 存储服务器socket {port: socket}
|
||||||
self.is_listening = False
|
self.is_listening = False
|
||||||
self.receive_callback: Optional[Callable] = None
|
self.receive_callback = None
|
||||||
self.timeout = timeout
|
|
||||||
self.chunk_size = chunk_size
|
|
||||||
self.lock = threading.Lock()
|
|
||||||
|
|
||||||
def _create_socket(self) -> socket.socket:
|
def send_file(self, file_data: bytes, target_ip: str, target_port: int) -> Tuple[bool, str]:
|
||||||
"""创建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:
|
try:
|
||||||
with self._create_socket() as sock:
|
# 创建IPv6 TCP socket
|
||||||
sock.settimeout(self.timeout)
|
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
|
||||||
|
# 设置超时时间
|
||||||
|
sock.settimeout(30)
|
||||||
|
|
||||||
logger.info(f"连接到 [{target_ip}]:{target_port}...")
|
print(f"连接到 [{target_ip}]:{target_port}...")
|
||||||
|
|
||||||
|
# 连接到目标
|
||||||
sock.connect((target_ip, target_port, 0, 0))
|
sock.connect((target_ip, target_port, 0, 0))
|
||||||
logger.info("连接成功")
|
print("连接成功")
|
||||||
|
|
||||||
# 发送数据长度
|
# 发送数据长度(8字节,大端序)
|
||||||
data_length = len(data)
|
data_length = len(file_data)
|
||||||
sock.send(struct.pack('!Q', data_length))
|
sock.send(struct.pack('!Q', data_length))
|
||||||
|
|
||||||
# 发送数据
|
# 发送实际数据
|
||||||
total_sent = 0
|
total_sent = 0
|
||||||
while total_sent < data_length:
|
chunk_size = 4096
|
||||||
remaining = data_length - total_sent
|
|
||||||
send_size = min(self.chunk_size, remaining)
|
|
||||||
|
|
||||||
sent = sock.send(data[total_sent:total_sent + send_size])
|
while total_sent < data_length:
|
||||||
|
# 计算本次发送的数据量
|
||||||
|
remaining = data_length - total_sent
|
||||||
|
send_size = min(chunk_size, remaining)
|
||||||
|
|
||||||
|
# 发送数据块
|
||||||
|
sent = sock.send(file_data[total_sent:total_sent + send_size])
|
||||||
if sent == 0:
|
if sent == 0:
|
||||||
raise ConnectionError("连接中断")
|
raise ConnectionError("连接中断")
|
||||||
|
|
||||||
total_sent += sent
|
total_sent += sent
|
||||||
|
|
||||||
# 进度显示
|
# 显示进度
|
||||||
if total_sent % (self.chunk_size * 10) == 0 or total_sent == data_length:
|
progress = (total_sent / data_length) * 100
|
||||||
progress = (total_sent / data_length) * 100
|
if total_sent % (chunk_size * 10) == 0 or total_sent == data_length:
|
||||||
logger.info(f"发送进度: {progress:.1f}% ({total_sent}/{data_length} bytes)")
|
print(f"发送进度: {progress:.1f}% ({total_sent}/{data_length} bytes)")
|
||||||
|
|
||||||
logger.info("数据发送完成")
|
print("文件发送完成")
|
||||||
return True, "发送成功"
|
return True, "发送成功"
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
error_msg = "连接超时"
|
error_msg = "连接超时"
|
||||||
logger.error(error_msg)
|
print(error_msg)
|
||||||
return False, error_msg
|
return False, error_msg
|
||||||
except ConnectionRefusedError:
|
except ConnectionRefusedError:
|
||||||
error_msg = "连接被拒绝"
|
error_msg = "连接被拒绝,目标可能未启动服务"
|
||||||
logger.error(error_msg)
|
print(error_msg)
|
||||||
return False, error_msg
|
return False, error_msg
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_msg = f"发送失败: {e}"
|
error_msg = f"发送失败: {e}"
|
||||||
logger.error(error_msg)
|
print(error_msg)
|
||||||
return False, error_msg
|
return False, error_msg
|
||||||
|
|
||||||
def start_server(self, listen_port: int, callback: Callable) -> Tuple[bool, str]:
|
def start_server(self, listen_port: int, callback: Callable) -> Tuple[bool, str]:
|
||||||
"""
|
"""
|
||||||
启动TCP服务器监听指定端口
|
启动TCP服务器监听指定端口
|
||||||
|
|
||||||
|
Args:
|
||||||
|
listen_port: 监听端口
|
||||||
|
callback: 接收到数据时的回调函数
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple[bool, str]: (是否成功, 错误信息)
|
||||||
"""
|
"""
|
||||||
with self.lock:
|
if listen_port in self.servers:
|
||||||
if listen_port in self.servers:
|
return False, f"端口 {listen_port} 已经在监听中"
|
||||||
return False, f"端口 {listen_port} 已经在监听中"
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
server_socket = self._create_socket()
|
# 创建IPv6 TCP socket
|
||||||
server_socket.bind(('::', listen_port))
|
server_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||||
server_socket.listen(5)
|
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
|
||||||
self.servers[listen_port] = server_socket
|
# 绑定到所有IPv6地址
|
||||||
self.receive_callback = callback
|
server_socket.bind(('::', listen_port))
|
||||||
self.is_listening = True
|
server_socket.listen(5)
|
||||||
|
|
||||||
logger.info(f"服务器开始监听端口 {listen_port}")
|
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,),
|
|
||||||
daemon=True,
|
|
||||||
name=f"Server-{listen_port}"
|
|
||||||
)
|
|
||||||
thread.start()
|
|
||||||
|
|
||||||
return True, f"服务器启动成功,监听端口 {listen_port}"
|
# 启动监听线程
|
||||||
|
thread = threading.Thread(target=self._accept_connections, args=(listen_port,))
|
||||||
|
thread.daemon = True
|
||||||
|
thread.start()
|
||||||
|
|
||||||
except PermissionError:
|
return True, f"服务器启动成功,监听端口 {listen_port}"
|
||||||
error_msg = f"权限不足,无法监听端口 {listen_port}"
|
|
||||||
logger.error(error_msg)
|
except PermissionError:
|
||||||
return False, error_msg
|
error_msg = f"权限不足,无法监听端口 {listen_port}"
|
||||||
except Exception as e:
|
print(error_msg)
|
||||||
error_msg = f"启动服务器失败: {e}"
|
return False, error_msg
|
||||||
logger.error(error_msg)
|
except Exception as e:
|
||||||
return False, error_msg
|
error_msg = f"启动服务器失败: {e}"
|
||||||
|
print(error_msg)
|
||||||
|
return False, error_msg
|
||||||
|
|
||||||
def _accept_connections(self, port: int):
|
def _accept_connections(self, port: int):
|
||||||
"""接受连接请求"""
|
"""接受连接请求"""
|
||||||
@@ -123,103 +129,105 @@ class TCPIPv6Transporter:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
while self.is_listening:
|
while self.is_listening:
|
||||||
logger.info(f"等待连接在端口 {port}...")
|
print(f"等待连接在端口 {port}...")
|
||||||
client_socket, client_addr = server_socket.accept()
|
client_socket, client_addr = server_socket.accept()
|
||||||
|
|
||||||
logger.info(f"接收到来自 [{client_addr[0]}]:{client_addr[1]} 的连接")
|
print(f"接收到来自 [{client_addr[0]}]:{client_addr[1]} 的连接")
|
||||||
|
|
||||||
# 处理客户端连接
|
# 处理客户端连接
|
||||||
client_thread = threading.Thread(
|
client_thread = threading.Thread(
|
||||||
target=self._handle_client,
|
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()
|
client_thread.start()
|
||||||
|
|
||||||
except OSError:
|
|
||||||
# 正常关闭时的错误
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if self.is_listening:
|
if self.is_listening:
|
||||||
logger.error(f"接受连接错误: {e}")
|
print(f"接受连接错误: {e}")
|
||||||
|
|
||||||
def _handle_client(self, client_socket: socket.socket, client_addr: Tuple):
|
def _handle_client(self, client_socket: socket.socket, client_addr: Tuple):
|
||||||
"""处理客户端连接"""
|
"""处理客户端连接"""
|
||||||
try:
|
try:
|
||||||
client_socket.settimeout(self.timeout)
|
# 设置超时时间
|
||||||
|
client_socket.settimeout(30)
|
||||||
|
|
||||||
# 接收数据长度
|
# 接收数据长度(8字节,大端序)
|
||||||
length_data = self._receive_all(client_socket, 8)
|
length_data = client_socket.recv(8)
|
||||||
if not length_data:
|
if not length_data or len(length_data) != 8:
|
||||||
raise ValueError("未接收到数据长度信息")
|
raise ValueError("无效的数据长度信息")
|
||||||
|
|
||||||
data_length = struct.unpack('!Q', length_data)[0]
|
data_length = struct.unpack('!Q', length_data)[0]
|
||||||
logger.info(f"准备接收 {data_length} bytes 数据")
|
print(f"准备接收 {data_length} bytes 数据")
|
||||||
|
|
||||||
# 接收数据
|
# 接收实际数据
|
||||||
received_data = self._receive_all(client_socket, data_length)
|
received_data = b''
|
||||||
|
total_received = 0
|
||||||
|
chunk_size = 4096
|
||||||
|
|
||||||
logger.info("数据接收完成")
|
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)")
|
||||||
|
|
||||||
|
print("文件接收完成")
|
||||||
|
|
||||||
|
# 调用回调函数处理接收到的数据
|
||||||
if self.receive_callback:
|
if self.receive_callback:
|
||||||
self.receive_callback(received_data, client_addr)
|
self.receive_callback(received_data, client_addr)
|
||||||
else:
|
else:
|
||||||
logger.warning("未设置接收回调函数")
|
print("警告: 未设置接收回调函数")
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
logger.error("接收数据超时")
|
print("接收数据超时")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"处理客户端数据错误: {e}")
|
print(f"处理客户端数据错误: {e}")
|
||||||
finally:
|
finally:
|
||||||
try:
|
client_socket.close()
|
||||||
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]:
|
def stop_server(self, port: int) -> Tuple[bool, str]:
|
||||||
"""
|
"""
|
||||||
停止指定端口的服务器
|
停止指定端口的服务器
|
||||||
|
|
||||||
|
Args:
|
||||||
|
port: 要停止的端口
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple[bool, str]: (是否成功, 错误信息)
|
||||||
"""
|
"""
|
||||||
with self.lock:
|
if port not in self.servers:
|
||||||
if port not in self.servers:
|
return False, f"端口 {port} 未在监听中"
|
||||||
return False, f"端口 {port} 未在监听中"
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
server_socket = self.servers[port]
|
server_socket = self.servers[port]
|
||||||
server_socket.close()
|
server_socket.close()
|
||||||
del self.servers[port]
|
del self.servers[port]
|
||||||
|
|
||||||
if not self.servers:
|
# 如果所有服务器都停止了,设置监听标志为False
|
||||||
self.is_listening = False
|
if not self.servers:
|
||||||
|
self.is_listening = False
|
||||||
|
|
||||||
logger.info(f"端口 {port} 服务器已停止")
|
return True, f"端口 {port} 服务器已停止"
|
||||||
return True, f"端口 {port} 服务器已停止"
|
except Exception as e:
|
||||||
except Exception as e:
|
return False, f"停止服务器失败: {e}"
|
||||||
error_msg = f"停止服务器失败: {e}"
|
|
||||||
logger.error(error_msg)
|
|
||||||
return False, error_msg
|
|
||||||
|
|
||||||
def stop_all_servers(self) -> Tuple[bool, str]:
|
def stop_all_servers(self) -> Tuple[bool, str]:
|
||||||
"""停止所有服务器"""
|
"""停止所有服务器"""
|
||||||
success_count = 0
|
success_count = 0
|
||||||
|
error_count = 0
|
||||||
error_msgs = []
|
error_msgs = []
|
||||||
|
|
||||||
ports = list(self.servers.keys())
|
ports = list(self.servers.keys())
|
||||||
@@ -228,21 +236,18 @@ class TCPIPv6Transporter:
|
|||||||
if success:
|
if success:
|
||||||
success_count += 1
|
success_count += 1
|
||||||
else:
|
else:
|
||||||
|
error_count += 1
|
||||||
error_msgs.append(msg)
|
error_msgs.append(msg)
|
||||||
|
|
||||||
if error_msgs:
|
if error_count == 0:
|
||||||
return False, f"成功停止 {success_count} 个,失败 {len(error_msgs)} 个: {', '.join(error_msgs)}"
|
|
||||||
else:
|
|
||||||
return True, f"成功停止 {success_count} 个服务器"
|
return True, f"成功停止 {success_count} 个服务器"
|
||||||
|
else:
|
||||||
|
return False, f"成功停止 {success_count} 个,失败 {error_count} 个: {', '.join(error_msgs)}"
|
||||||
|
|
||||||
def get_listening_ports(self) -> List[int]:
|
def get_listening_ports(self) -> list:
|
||||||
"""获取当前正在监听的端口列表"""
|
"""获取当前正在监听的端口列表"""
|
||||||
return list(self.servers.keys())
|
return list(self.servers.keys())
|
||||||
|
|
||||||
def is_port_listening(self, port: int) -> bool:
|
def is_port_listening(self, port: int) -> bool:
|
||||||
"""检查指定端口是否在监听中"""
|
"""检查指定端口是否在监听中"""
|
||||||
return port in self.servers
|
return port in self.servers
|
||||||
|
|
||||||
def __del__(self):
|
|
||||||
"""析构函数,清理资源"""
|
|
||||||
self.stop_all_servers()
|
|
||||||
|
|||||||
+113
-130
@@ -1,59 +1,25 @@
|
|||||||
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from typing import List, Tuple
|
|
||||||
from cryptography.hazmat.primitives import serialization, hashes
|
from cryptography.hazmat.primitives import serialization, hashes
|
||||||
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
||||||
from cryptography.hazmat.backends import default_backend
|
from cryptography.hazmat.backends import default_backend
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
class RSACrypto:
|
||||||
|
# RSA加密的最大数据块大小(2048位密钥)
|
||||||
class RSACryptoManager:
|
|
||||||
# RSA加密配置
|
|
||||||
KEY_SIZE = 2048
|
|
||||||
MAX_BLOCK_SIZE = 190 # 2048/8 - 42(填充开销)
|
MAX_BLOCK_SIZE = 190 # 2048/8 - 42(填充开销)
|
||||||
ENCRYPTED_BLOCK_SIZE = 256 # 2048/8
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def generate_key_pair(private_key_path: str, public_key_path: str) -> Tuple[bool, str]:
|
def load_public_key(public_key_path):
|
||||||
"""生成RSA密钥对"""
|
"""
|
||||||
try:
|
从文件加载公钥
|
||||||
private_key = rsa.generate_private_key(
|
|
||||||
public_exponent=65537,
|
|
||||||
key_size=RSACryptoManager.KEY_SIZE,
|
|
||||||
backend=default_backend()
|
|
||||||
)
|
|
||||||
|
|
||||||
# 保存私钥
|
Args:
|
||||||
with open(private_key_path, 'wb') as f:
|
public_key_path: 公钥文件路径
|
||||||
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}")
|
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PublicKey: 加载的公钥对象
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
with open(public_key_path, 'rb') as f:
|
with open(public_key_path, 'rb') as f:
|
||||||
pem_data = f.read()
|
pem_data = f.read()
|
||||||
@@ -65,11 +31,16 @@ class RSACryptoManager:
|
|||||||
raise ValueError(f"加载公钥失败: {e}")
|
raise ValueError(f"加载公钥失败: {e}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def load_private_key(private_key_path: str):
|
def load_private_key(private_key_path):
|
||||||
"""从文件加载私钥"""
|
"""
|
||||||
if not os.path.exists(private_key_path):
|
从文件加载私钥
|
||||||
raise FileNotFoundError(f"私钥文件不存在: {private_key_path}")
|
|
||||||
|
|
||||||
|
Args:
|
||||||
|
private_key_path: 私钥文件路径
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PrivateKey: 加载的私钥对象
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
with open(private_key_path, 'rb') as f:
|
with open(private_key_path, 'rb') as f:
|
||||||
pem_data = f.read()
|
pem_data = f.read()
|
||||||
@@ -82,61 +53,84 @@ class RSACryptoManager:
|
|||||||
raise ValueError(f"加载私钥失败: {e}")
|
raise ValueError(f"加载私钥失败: {e}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def encrypt_data(data: bytes, public_key_path: str) -> bytes:
|
def encrypt_block(block_data, public_key_path):
|
||||||
"""加密数据"""
|
"""
|
||||||
if not data:
|
使用公钥加密单个数据块
|
||||||
raise ValueError("数据为空")
|
|
||||||
|
|
||||||
# 分割数据为适合RSA加密的块
|
Args:
|
||||||
blocks = []
|
block_data: 要加密的数据块(不超过190字节)
|
||||||
for i in range(0, len(data), RSACryptoManager.MAX_BLOCK_SIZE):
|
public_key_path: 公钥文件路径
|
||||||
block = data[i:i + RSACryptoManager.MAX_BLOCK_SIZE]
|
|
||||||
blocks.append(block)
|
|
||||||
|
|
||||||
# 加密所有块
|
Returns:
|
||||||
encrypted_blocks = RSACryptoManager.encrypt_blocks(blocks, public_key_path)
|
bytes: 加密后的数据块
|
||||||
|
"""
|
||||||
|
# 验证数据块大小
|
||||||
|
if len(block_data) > RSACrypto.MAX_BLOCK_SIZE:
|
||||||
|
raise ValueError(f"数据块大小超过限制: {len(block_data)} > {RSACrypto.MAX_BLOCK_SIZE}")
|
||||||
|
|
||||||
# 合并加密后的块
|
# 加载公钥
|
||||||
return b''.join(encrypted_blocks)
|
public_key = RSACrypto.load_public_key(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}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def decrypt_data(encrypted_data: bytes, private_key_path: str) -> bytes:
|
def decrypt_block(encrypted_block, private_key_path):
|
||||||
"""解密数据"""
|
"""
|
||||||
if not encrypted_data:
|
使用私钥解密单个数据块
|
||||||
raise ValueError("加密数据为空")
|
|
||||||
|
|
||||||
# 验证加密数据长度
|
Args:
|
||||||
if len(encrypted_data) % RSACryptoManager.ENCRYPTED_BLOCK_SIZE != 0:
|
encrypted_block: 加密的数据块
|
||||||
raise ValueError("无效的加密数据长度")
|
private_key_path: 私钥文件路径
|
||||||
|
|
||||||
# 分割为加密块
|
Returns:
|
||||||
encrypted_blocks = []
|
bytes: 解密后的原始数据块
|
||||||
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)
|
private_key = RSACrypto.load_private_key(private_key_path)
|
||||||
|
|
||||||
# 解密所有块
|
# 解密数据块
|
||||||
decrypted_blocks = RSACryptoManager.decrypt_blocks(encrypted_blocks, private_key_path)
|
try:
|
||||||
|
decrypted_block = private_key.decrypt(
|
||||||
# 合并解密后的块
|
encrypted_block,
|
||||||
return b''.join(decrypted_blocks)
|
padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return decrypted_block
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(f"解密数据块失败: {e}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def encrypt_blocks(blocks: List[bytes], public_key_path: str) -> List[bytes]:
|
def encrypt_blocks(blocks, public_key_path):
|
||||||
"""批量加密多个数据块"""
|
"""
|
||||||
public_key = RSACryptoManager.load_public_key(public_key_path)
|
批量加密多个数据块
|
||||||
|
|
||||||
|
Args:
|
||||||
|
blocks: 数据块列表
|
||||||
|
public_key_path: 公钥文件路径
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list: 加密后的数据块列表
|
||||||
|
"""
|
||||||
encrypted_blocks = []
|
encrypted_blocks = []
|
||||||
|
|
||||||
for i, block in enumerate(blocks):
|
for i, block in enumerate(blocks):
|
||||||
try:
|
try:
|
||||||
encrypted_block = public_key.encrypt(
|
encrypted_block = RSACrypto.encrypt_block(block, public_key_path)
|
||||||
block,
|
|
||||||
padding.OAEP(
|
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
|
||||||
label=None
|
|
||||||
)
|
|
||||||
)
|
|
||||||
encrypted_blocks.append(encrypted_block)
|
encrypted_blocks.append(encrypted_block)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"加密第 {i} 个数据块失败: {e}")
|
raise ValueError(f"加密第 {i} 个数据块失败: {e}")
|
||||||
@@ -144,21 +138,22 @@ class RSACryptoManager:
|
|||||||
return encrypted_blocks
|
return encrypted_blocks
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def decrypt_blocks(encrypted_blocks: List[bytes], private_key_path: str) -> List[bytes]:
|
def decrypt_blocks(encrypted_blocks, private_key_path):
|
||||||
"""批量解密多个数据块"""
|
"""
|
||||||
private_key = RSACryptoManager.load_private_key(private_key_path)
|
批量解密多个数据块
|
||||||
|
|
||||||
|
Args:
|
||||||
|
encrypted_blocks: 加密的数据块列表
|
||||||
|
private_key_path: 私钥文件路径
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list: 解密后的原始数据块列表
|
||||||
|
"""
|
||||||
decrypted_blocks = []
|
decrypted_blocks = []
|
||||||
|
|
||||||
for i, encrypted_block in enumerate(encrypted_blocks):
|
for i, encrypted_block in enumerate(encrypted_blocks):
|
||||||
try:
|
try:
|
||||||
decrypted_block = private_key.decrypt(
|
decrypted_block = RSACrypto.decrypt_block(encrypted_block, private_key_path)
|
||||||
encrypted_block,
|
|
||||||
padding.OAEP(
|
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
|
||||||
label=None
|
|
||||||
)
|
|
||||||
)
|
|
||||||
decrypted_blocks.append(decrypted_block)
|
decrypted_blocks.append(decrypted_block)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"解密第 {i} 个数据块失败: {e}")
|
raise ValueError(f"解密第 {i} 个数据块失败: {e}")
|
||||||
@@ -166,36 +161,24 @@ class RSACryptoManager:
|
|||||||
return decrypted_blocks
|
return decrypted_blocks
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def verify_key_pair(private_key_path: str, public_key_path: str) -> bool:
|
def get_max_block_size():
|
||||||
"""验证私钥和公钥是否匹配"""
|
"""
|
||||||
try:
|
获取最大数据块大小
|
||||||
private_key = RSACryptoManager.load_private_key(private_key_path)
|
|
||||||
public_key = RSACryptoManager.load_public_key(public_key_path)
|
|
||||||
|
|
||||||
# 生成测试数据
|
Returns:
|
||||||
test_data = b"test_data_for_verification"
|
int: 最大数据块大小(字节)
|
||||||
|
"""
|
||||||
|
return RSACrypto.MAX_BLOCK_SIZE
|
||||||
|
|
||||||
# 使用公钥加密
|
@staticmethod
|
||||||
encrypted = public_key.encrypt(
|
def validate_block_size(block_data):
|
||||||
test_data,
|
"""
|
||||||
padding.OAEP(
|
验证数据块大小是否合法
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
|
||||||
label=None
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# 使用私钥解密
|
Args:
|
||||||
decrypted = private_key.decrypt(
|
block_data: 数据块
|
||||||
encrypted,
|
|
||||||
padding.OAEP(
|
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
|
||||||
label=None
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return decrypted == test_data
|
Returns:
|
||||||
|
bool: 是否合法
|
||||||
except Exception:
|
"""
|
||||||
return False
|
return len(block_data) <= RSACrypto.MAX_BLOCK_SIZE
|
||||||
|
|||||||
Reference in New Issue
Block a user