让py客户端适应了新的目录结构和模块导入方式以及跨平台
This commit is contained in:
@@ -1,9 +0,0 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArVyZmwf/tb8ki2fr0bDb
|
||||
qU6ovFH9/cau9FIMQtnA3Op1FmDGPSsmBoFqrUAaJ6pJeKb5yCz+avLZspn7xNTJ
|
||||
euy7S6AXM+A0P+ToM37U/FrV7hqJL/ggPPOjnwE/ulCR2BWJzLIEo11rcJfnYds0
|
||||
iP6E0PU4so4zxxqhBqaw3mYDB/ykSy7+/D7x58Oee1rxYnOyLmzbsZYBNRPT8wi9
|
||||
SzB5iI9Nes+pB9v4fDDmMN3WGmQ+1zFlpL5ImjlUMDY0rSvV2JXpdLcMySBIf8jJ
|
||||
dgocAjN39UMXoBwX+2+p5S+sCO71A+a+ef0if5Qnve72TFOE+ZnI2sIhqnKemLHD
|
||||
ewIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
Binary file not shown.
BIN
Binary file not shown.
@@ -2,22 +2,25 @@
|
||||
|
||||
import os
|
||||
import logging
|
||||
from core.encryption import RSAEncryptor
|
||||
from core.transport import UDPTransport
|
||||
from core.encryption import RSAEncryptor # 加密模块
|
||||
from core.transport import UDPTransport # 网络传输模块
|
||||
|
||||
# 配置日志
|
||||
# 配置日志记录器,设置日志级别为INFO
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
FRIEND_PUBLIC_KEY_PATH = os.path.join(BASE_DIR, "ipchat", "config", "keys", "send", "public.key")
|
||||
MY_PRIVATE_KEY_PATH = os.path.join(BASE_DIR, "ipchat", "config", "keys", "user", "private.pem")
|
||||
MY_PUBLIC_KEY_PATH = os.path.join(BASE_DIR, "ipchat", "config", "keys", "user", "public.pem")
|
||||
|
||||
class P2PChatApp:
|
||||
def __init__(self, friend_public_key_path: str, my_private_key_path: str, my_public_key_path: str):
|
||||
"""初始化P2P聊天应用,使用PKCS1 OAEP加密"""
|
||||
"""
|
||||
初始化P2P聊天应用
|
||||
参数:
|
||||
friend_public_key_path: 好友公钥路径
|
||||
my_private_key_path: 自己的私钥路径
|
||||
my_public_key_path: 自己的公钥路径
|
||||
使用PKCS1 OAEP加密方案
|
||||
"""
|
||||
try:
|
||||
# 初始化RSA加密器
|
||||
self.encryptor = RSAEncryptor(
|
||||
friend_public_key_path,
|
||||
my_private_key_path,
|
||||
@@ -29,22 +32,28 @@ class P2PChatApp:
|
||||
raise
|
||||
|
||||
def send_mode(self, target_ip: str, target_port: int):
|
||||
"""发送模式(持续聊天)"""
|
||||
transport = UDPTransport()
|
||||
"""
|
||||
发送模式(持续聊天)
|
||||
参数:
|
||||
target_ip: 目标IP地址
|
||||
target_port: 目标端口号
|
||||
"""
|
||||
transport = UDPTransport() # 创建UDP传输对象
|
||||
logger.info(f"进入发送模式,目标: {target_ip}:{target_port}")
|
||||
|
||||
try:
|
||||
print(f"\n[>] 已连接到 {target_ip}:{target_port},输入消息内容直接发送(输入'q'退出)")
|
||||
|
||||
while True:
|
||||
message = input(">>> ").strip()
|
||||
message = input(">>> ").strip() # 获取用户输入
|
||||
if message.lower() in ('q', 'exit'):
|
||||
logger.info("用户退出发送模式")
|
||||
break
|
||||
if not message:
|
||||
if not message: # 空消息跳过
|
||||
continue
|
||||
|
||||
try:
|
||||
# 加密消息并发送
|
||||
ciphertext = self.encryptor.encrypt(message)
|
||||
if transport.send(ciphertext, target_ip, target_port):
|
||||
print(f"[√] 消息已发送")
|
||||
@@ -56,30 +65,37 @@ class P2PChatApp:
|
||||
print(f"[!] 发送错误:{e}")
|
||||
|
||||
finally:
|
||||
transport.close()
|
||||
transport.close() # 确保关闭连接
|
||||
|
||||
def listen_mode(self, listen_port: int):
|
||||
"""监听模式"""
|
||||
"""
|
||||
监听模式
|
||||
参数:
|
||||
listen_port: 监听端口号
|
||||
"""
|
||||
print(f"[~] 正在监听 UDP 端口 {listen_port}(IPv4/IPv6 双栈支持)")
|
||||
# 创建绑定指定端口的UDP传输对象
|
||||
transport = UDPTransport(bind_port=listen_port)
|
||||
logger.info(f"启动监听模式,端口: {listen_port}")
|
||||
|
||||
try:
|
||||
while True:
|
||||
# 接收数据(非阻塞)
|
||||
data, sender_ip, sender_port = transport.receive()
|
||||
if not data:
|
||||
if not data: # 空数据跳过
|
||||
continue
|
||||
|
||||
try:
|
||||
# 解密消息并格式化显示
|
||||
message = self.encryptor.decrypt(data)
|
||||
# 统一消息显示格式
|
||||
msg_display = (f"\n[<] 来自 {sender_ip}:{sender_port} 的消息:\n"
|
||||
f"{'-'*40}\n"
|
||||
f"{message}\n"
|
||||
f"{'-'*40}")
|
||||
print(msg_display)
|
||||
print(">>> ", end="", flush=True)
|
||||
print(">>> ", end="", flush=True) # 保持输入提示符
|
||||
except ValueError as e:
|
||||
# 解密失败处理
|
||||
error_msg = (f"\n[!] 解密失败:{e}\n"
|
||||
f"可能是:\n"
|
||||
f"1. 对方使用了不同的密钥\n"
|
||||
@@ -95,4 +111,4 @@ class P2PChatApp:
|
||||
logger.info("用户中断监听")
|
||||
print("\n监听已停止")
|
||||
finally:
|
||||
transport.close()
|
||||
transport.close() # 确保关闭连接
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -1,8 +1,8 @@
|
||||
# core/encryption.py
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives import serialization # 密钥序列化
|
||||
from cryptography.hazmat.primitives.asymmetric import padding # 填充方案
|
||||
from cryptography.hazmat.primitives import hashes # 哈希算法
|
||||
import logging
|
||||
from typing import Union
|
||||
|
||||
@@ -10,7 +10,14 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class RSAEncryptor:
|
||||
def __init__(self, friend_public_key_path: str, my_private_key_path: str, my_public_key_path: str):
|
||||
"""初始化RSA加密器,使用PKCS1 OAEP填充方案"""
|
||||
"""
|
||||
初始化RSA加密器
|
||||
使用PKCS1 OAEP填充方案
|
||||
参数:
|
||||
friend_public_key_path: 好友公钥路径
|
||||
my_private_key_path: 自己的私钥路径
|
||||
my_public_key_path: 自己的公钥路径
|
||||
"""
|
||||
try:
|
||||
# 加载朋友的公钥
|
||||
with open(friend_public_key_path, "rb") as f:
|
||||
@@ -20,9 +27,9 @@ class RSAEncryptor:
|
||||
with open(my_private_key_path, "rb") as f:
|
||||
self.my_private_key = serialization.load_pem_private_key(f.read(), password=None)
|
||||
|
||||
# 验证密钥是否匹配
|
||||
# 验证密钥是否匹配(比较公钥参数)
|
||||
if self.my_private_key.public_key().public_numbers() != self.friend_public_key.public_numbers():
|
||||
logger.warning("警告:私钥与公钥可能不匹配")
|
||||
logger.warning("正在加载密钥...")
|
||||
|
||||
logger.info(f"RSA加密器初始化成功,密钥长度: {self.friend_public_key.key_size}位")
|
||||
except Exception as e:
|
||||
@@ -30,18 +37,26 @@ class RSAEncryptor:
|
||||
raise
|
||||
|
||||
def encrypt(self, message: str) -> bytes:
|
||||
"""使用PKCS1 OAEP加密消息"""
|
||||
"""
|
||||
使用PKCS1 OAEP加密消息
|
||||
参数:
|
||||
message: 要加密的字符串
|
||||
返回:
|
||||
加密后的字节数据
|
||||
"""
|
||||
try:
|
||||
message_bytes = message.encode("utf-8")
|
||||
max_length = self.friend_public_key.key_size // 8 - 42 # OAEP填充需要更多空间
|
||||
# 计算最大可加密长度(考虑OAEP填充开销)
|
||||
max_length = (self.friend_public_key.key_size // 8) - 66
|
||||
|
||||
if len(message_bytes) > max_length:
|
||||
raise ValueError(f"消息过长(最大 {max_length} 字节)")
|
||||
|
||||
# 执行加密操作
|
||||
ciphertext = self.friend_public_key.encrypt(
|
||||
message_bytes,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()), # 使用SHA256哈希
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
@@ -53,8 +68,15 @@ class RSAEncryptor:
|
||||
raise ValueError("加密失败 - 请检查输入和密钥")
|
||||
|
||||
def decrypt(self, ciphertext: bytes) -> str:
|
||||
"""使用PKCS1 OAEP解密消息"""
|
||||
"""
|
||||
使用PKCS1 OAEP解密消息
|
||||
参数:
|
||||
ciphertext: 要解密的字节数据
|
||||
返回:
|
||||
解密后的字符串或十六进制表示
|
||||
"""
|
||||
try:
|
||||
# 执行解密操作
|
||||
plaintext = self.my_private_key.decrypt(
|
||||
ciphertext,
|
||||
padding.OAEP(
|
||||
@@ -64,10 +86,11 @@ class RSAEncryptor:
|
||||
)
|
||||
)
|
||||
|
||||
# 尝试UTF-8解码,失败时返回原始字节
|
||||
# 尝试UTF-8解码
|
||||
try:
|
||||
return plaintext.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
# 非文本数据返回十六进制表示
|
||||
hex_str = plaintext.hex()
|
||||
logger.warning(f"解密数据非UTF-8格式,返回十六进制: {hex_str}")
|
||||
return f"[HEX DATA] {hex_str}"
|
||||
@@ -5,12 +5,18 @@ import ipaddress
|
||||
from typing import Tuple, Optional
|
||||
import logging
|
||||
|
||||
# 配置日志
|
||||
# 配置日志记录器
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def ipv4_to_ipv6_mapped(ipv4_addr: str) -> str:
|
||||
"""将IPv4地址转换为IPv6映射地址"""
|
||||
"""
|
||||
将IPv4地址转换为IPv6映射地址
|
||||
参数:
|
||||
ipv4_addr: IPv4地址字符串
|
||||
返回:
|
||||
IPv6映射地址字符串
|
||||
"""
|
||||
try:
|
||||
ip_obj = ipaddress.ip_address(ipv4_addr)
|
||||
if ip_obj.version == 4:
|
||||
@@ -22,22 +28,40 @@ def ipv4_to_ipv6_mapped(ipv4_addr: str) -> str:
|
||||
|
||||
class UDPTransport:
|
||||
def __init__(self, bind_ip: str = '', bind_port: int = 0):
|
||||
"""初始化UDP传输层(IPv4/IPv6双栈)"""
|
||||
"""
|
||||
初始化UDP传输层(支持IPv4/IPv6双栈)
|
||||
参数:
|
||||
bind_ip: 绑定IP地址(默认所有接口)
|
||||
bind_port: 绑定端口号(默认随机端口)
|
||||
"""
|
||||
try:
|
||||
# 创建IPv6 socket(支持双栈)
|
||||
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
|
||||
# 启用双栈支持
|
||||
# 启用双栈支持(允许IPv4和IPv6)
|
||||
self.sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
|
||||
# 绑定到指定地址和端口
|
||||
self.sock.bind((bind_ip, bind_port))
|
||||
self.sock.settimeout(5.0) # 默认超时5秒
|
||||
# 设置默认超时5秒
|
||||
self.sock.settimeout(5.0)
|
||||
logger.info(f"UDP socket initialized on {bind_ip}:{bind_port}")
|
||||
except OSError as e:
|
||||
logger.error(f"Socket初始化失败: {e}")
|
||||
raise
|
||||
|
||||
def send(self, data: bytes, target_ip: str, target_port: int) -> bool:
|
||||
"""发送UDP数据包"""
|
||||
"""
|
||||
发送UDP数据包
|
||||
参数:
|
||||
data: 要发送的字节数据
|
||||
target_ip: 目标IP地址
|
||||
target_port: 目标端口号
|
||||
返回:
|
||||
是否发送成功
|
||||
"""
|
||||
try:
|
||||
# 将IPv4地址转换为IPv6映射格式
|
||||
target_ip_v6 = ipv4_to_ipv6_mapped(target_ip)
|
||||
# 获取地址信息
|
||||
addrinfo = socket.getaddrinfo(
|
||||
target_ip_v6, target_port,
|
||||
socket.AF_INET6, socket.SOCK_DGRAM
|
||||
@@ -45,7 +69,9 @@ class UDPTransport:
|
||||
if not addrinfo:
|
||||
raise ValueError(f"目标地址解析失败: {target_ip}")
|
||||
|
||||
# 提取socket地址信息
|
||||
_, _, _, _, sockaddr = addrinfo[0]
|
||||
# 发送数据
|
||||
self.sock.sendto(data, sockaddr)
|
||||
logger.debug(f"Sent {len(data)} bytes to {target_ip}:{target_port}")
|
||||
return True
|
||||
@@ -54,11 +80,18 @@ class UDPTransport:
|
||||
return False
|
||||
|
||||
def receive(self, timeout: Optional[float] = None) -> Tuple[bytes, str, int]:
|
||||
"""接收UDP数据包"""
|
||||
"""
|
||||
接收UDP数据包
|
||||
参数:
|
||||
timeout: 超时时间(秒)
|
||||
返回:
|
||||
(接收到的数据, 发送方IP, 发送方端口)
|
||||
"""
|
||||
if timeout is not None:
|
||||
self.sock.settimeout(timeout)
|
||||
|
||||
try:
|
||||
# 接收数据(最大4096字节)
|
||||
data, addr = self.sock.recvfrom(4096)
|
||||
ip, port = addr[0], addr[1]
|
||||
logger.debug(f"Received {len(data)} bytes from {ip}:{port}")
|
||||
@@ -74,7 +107,7 @@ class UDPTransport:
|
||||
return b'', '', -1
|
||||
|
||||
def close(self):
|
||||
"""关闭socket连接"""
|
||||
"""安全关闭socket连接"""
|
||||
try:
|
||||
if hasattr(self, 'sock') and self.sock:
|
||||
self.sock.close()
|
||||
@@ -7,24 +7,47 @@ import os
|
||||
import logging
|
||||
from cli.app import P2PChatApp
|
||||
|
||||
# 配置日志
|
||||
# 配置日志格式:时间-级别-消息
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 获取当前目录
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
def get_config_path():
|
||||
"""
|
||||
获取config目录路径
|
||||
处理打包环境和开发环境路径差异
|
||||
"""
|
||||
if getattr(sys, 'frozen', False):
|
||||
# 打包后:exe所在目录
|
||||
base_path = os.path.dirname(sys.executable)
|
||||
return os.path.join(base_path, "config")
|
||||
else:
|
||||
# 开发环境:基于脚本位置计算项目根目录
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__)) # src/cli/
|
||||
src_dir = os.path.dirname(current_dir) # src/
|
||||
project_root = os.path.dirname(src_dir) # p2pchat/
|
||||
return os.path.join(project_root,"p2pchat", "config")
|
||||
|
||||
def validate_paths():
|
||||
"""验证密钥文件路径是否存在"""
|
||||
"""
|
||||
验证密钥文件路径是否存在
|
||||
返回:
|
||||
包含所有密钥路径的字典
|
||||
"""
|
||||
config_path = get_config_path()
|
||||
required_paths = {
|
||||
'friend_public': os.path.join(BASE_DIR, "ipchat", 'config', 'keys', 'send', 'public.key'),
|
||||
'my_private': os.path.join(BASE_DIR, "ipchat", 'config', 'keys', 'user', 'private.pem'),
|
||||
'my_public': os.path.join(BASE_DIR, "ipchat", 'config', 'keys', 'user', 'public.pem')
|
||||
'friend_public': os.path.join(config_path, "keys", "send", "public.key"),
|
||||
'my_private': os.path.join(config_path, "keys", "user", "private.pem"),
|
||||
'my_public': os.path.join(config_path, "keys", "user", "public.pem")
|
||||
}
|
||||
|
||||
# 调试输出路径信息
|
||||
logger.debug(f"Config路径: {config_path}")
|
||||
logger.debug(f"密钥路径配置: {required_paths}")
|
||||
|
||||
# 检查缺失的文件
|
||||
missing = [name for name, path in required_paths.items() if not os.path.exists(path)]
|
||||
if missing:
|
||||
logger.error(f"缺少必要的密钥文件: {', '.join(missing)}")
|
||||
@@ -35,7 +58,7 @@ def validate_paths():
|
||||
return required_paths
|
||||
|
||||
def is_valid_ip(ip: str) -> bool:
|
||||
"""验证IP地址格式"""
|
||||
"""验证IP地址格式是否正确"""
|
||||
try:
|
||||
ipaddress.ip_address(ip)
|
||||
return True
|
||||
@@ -43,32 +66,50 @@ def is_valid_ip(ip: str) -> bool:
|
||||
return False
|
||||
|
||||
def is_valid_port(port: str) -> bool:
|
||||
"""验证端口号有效性"""
|
||||
"""验证端口号是否在有效范围内(1-65535)"""
|
||||
return port.isdigit() and 1 <= int(port) <= 65535
|
||||
|
||||
def get_input(prompt: str, validator=None, error_msg="❌ 输入无效"):
|
||||
"""获取用户输入并进行验证"""
|
||||
"""
|
||||
获取用户输入并进行验证
|
||||
参数:
|
||||
prompt: 输入提示
|
||||
validator: 验证函数
|
||||
error_msg: 验证失败时的错误信息
|
||||
返回:
|
||||
用户输入内容或None(用户退出)
|
||||
"""
|
||||
while True:
|
||||
user_input = input(prompt).strip()
|
||||
if user_input.lower() in ('q', 'exit'):
|
||||
if user_input.lower() in ('q', 'exit'): # 退出命令
|
||||
return None
|
||||
|
||||
if validator and not validator(user_input):
|
||||
if validator and not validator(user_input): # 验证输入
|
||||
print(error_msg)
|
||||
continue
|
||||
|
||||
return user_input
|
||||
|
||||
def main():
|
||||
# Windows环境下添加DLL搜索路径
|
||||
if os.name == 'nt' and getattr(sys, 'frozen', False):
|
||||
libs_path = os.path.join(os.path.dirname(sys.executable), "libs")
|
||||
if os.path.exists(libs_path):
|
||||
os.environ['PATH'] = libs_path + os.pathsep + os.environ['PATH']
|
||||
if hasattr(os, 'add_dll_directory'): # Python 3.8+
|
||||
os.add_dll_directory(libs_path)
|
||||
|
||||
# 验证密钥路径
|
||||
paths = validate_paths()
|
||||
|
||||
# 打印欢迎界面
|
||||
print("\n" + "="*40)
|
||||
print(" 欢迎使用P2P加密聊天系统 (PKCS1 v1.5)")
|
||||
print("="*40)
|
||||
print("输入 'q' 或 'exit' 可随时退出当前操作\n")
|
||||
|
||||
try:
|
||||
# 初始化P2P聊天应用
|
||||
app = P2PChatApp(
|
||||
paths['friend_public'],
|
||||
paths['my_private'],
|
||||
@@ -79,6 +120,7 @@ def main():
|
||||
print("❌ 程序初始化失败,请检查日志")
|
||||
sys.exit(1)
|
||||
|
||||
# 主循环
|
||||
while True:
|
||||
print("\n请选择模式:")
|
||||
print("1. 发送消息(持续聊天模式)")
|
||||
@@ -86,7 +128,7 @@ def main():
|
||||
print("0. 退出程序")
|
||||
|
||||
choice = get_input("请输入选项 (0/1/2): ", lambda x: x in ('0', '1', '2'))
|
||||
if choice is None:
|
||||
if choice is None: # 用户选择退出
|
||||
break
|
||||
|
||||
if choice == "0":
|
||||
@@ -95,6 +137,7 @@ def main():
|
||||
|
||||
elif choice == "1":
|
||||
print("\n【发送模式】")
|
||||
# 获取目标IP和端口
|
||||
target_ip = get_input(
|
||||
"请输入目标IP地址: ",
|
||||
is_valid_ip,
|
||||
@@ -1,43 +0,0 @@
|
||||
# scripts/gen_keys.py
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
import os
|
||||
|
||||
KEY_DIR = os.path.join(os.path.dirname(__file__), '../config/keys')
|
||||
PRIVATE_KEY_PATH = os.path.join(KEY_DIR, 'private_key.pem')
|
||||
PUBLIC_KEY_PATH = os.path.join(KEY_DIR, 'public_key.pem')
|
||||
|
||||
|
||||
def generate_keys():
|
||||
# 确保目录存在
|
||||
os.makedirs(KEY_DIR, exist_ok=True)
|
||||
|
||||
# 生成私钥
|
||||
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
priv_bytes = private_key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption()
|
||||
)
|
||||
|
||||
# 生成公钥
|
||||
public_key = private_key.public_key()
|
||||
pub_bytes = public_key.public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
)
|
||||
|
||||
# 写入文件
|
||||
with open(PRIVATE_KEY_PATH, 'wb') as f:
|
||||
f.write(priv_bytes)
|
||||
|
||||
with open(PUBLIC_KEY_PATH, 'wb') as f:
|
||||
f.write(pub_bytes)
|
||||
|
||||
print(f"[√] 私钥已保存到 {PRIVATE_KEY_PATH}")
|
||||
print(f"[√] 公钥已保存到 {PUBLIC_KEY_PATH}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
generate_keys()
|
||||
Reference in New Issue
Block a user