# cli/app.py import os import logging from core.encryption import RSAEncryptor from core.transport import UDPTransport # 配置日志 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加密""" try: self.encryptor = RSAEncryptor( friend_public_key_path, my_private_key_path, my_public_key_path ) logger.info("P2P聊天应用初始化完成") except Exception as e: logger.error(f"应用初始化失败: {e}") raise def send_mode(self, target_ip: str, target_port: int): """发送模式(持续聊天)""" transport = UDPTransport() logger.info(f"进入发送模式,目标: {target_ip}:{target_port}") try: print(f"\n[>] 已连接到 {target_ip}:{target_port},输入消息内容直接发送(输入'q'退出)") while True: message = input(">>> ").strip() if message.lower() in ('q', 'exit'): logger.info("用户退出发送模式") break if not message: continue try: ciphertext = self.encryptor.encrypt(message) if transport.send(ciphertext, target_ip, target_port): print(f"[√] 消息已发送") else: print(f"[!] 发送失败") except ValueError as e: print(f"[!] 错误:{e}") except Exception as e: print(f"[!] 发送错误:{e}") finally: transport.close() def listen_mode(self, listen_port: int): """监听模式""" print(f"[~] 正在监听 UDP 端口 {listen_port}(IPv4/IPv6 双栈支持)") transport = UDPTransport(bind_port=listen_port) logger.info(f"启动监听模式,端口: {listen_port}") try: while True: data, sender_ip, sender_port = transport.receive() 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) except ValueError as e: error_msg = (f"\n[!] 解密失败:{e}\n" f"可能是:\n" f"1. 对方使用了不同的密钥\n" f"2. 网络数据损坏\n" f"3. 使用了不兼容的加密方案") print(error_msg) print(">>> ", end="", flush=True) except Exception as e: print(f"\n[!] 处理消息时出错:{e}") print(">>> ", end="", flush=True) except KeyboardInterrupt: logger.info("用户中断监听") print("\n监听已停止") finally: transport.close()