py客户端增加了离线模式

This commit is contained in:
Alex
2025-08-02 21:26:52 +08:00
parent 20952226bb
commit ff623014d4
5 changed files with 88 additions and 43 deletions
BIN
View File
Binary file not shown.
Binary file not shown.
+88 -43
View File
@@ -5,49 +5,40 @@ import sys
import ipaddress
import os
import logging
import base64
from cli.app import P2PChatApp
# 配置日志格式:时间-级别-消息
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def get_config_path():
"""
获取config目录路径
处理打包环境和开发环境路径差异
"""
def get_base_path():
"""获取资源基础路径"""
if getattr(sys, 'frozen', False):
# 打包后:exe所在目录
base_path = os.path.dirname(sys.executable)
return os.path.join(base_path, "config")
# 确保在打包模式下使用正确的config路径
return os.path.join(base_path, "ipchat") if not os.path.exists(os.path.join(base_path, "config")) else base_path
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")
# 开发环境:当前脚本所在目录(ipchat目录)
return os.path.dirname(os.path.abspath(__file__))
def validate_paths():
"""
验证密钥文件路径是否存在
返回:
包含所有密钥路径的字典
"""
config_path = get_config_path()
"""验证密钥文件路径是否存在"""
base_path = get_base_path()
required_paths = {
'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")
'friend_public': os.path.join(base_path, "config", "keys", "send", "public.key"),
'my_private': os.path.join(base_path, "config", "keys", "user", "private.pem"),
'my_public': os.path.join(base_path, "config", "keys", "user", "public.pem")
}
# 调试输出路径信息
logger.debug(f"Config路径: {config_path}")
logger.debug(f"基础路径: {base_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)}")
@@ -58,7 +49,7 @@ def validate_paths():
return required_paths
def is_valid_ip(ip: str) -> bool:
"""验证IP地址格式是否正确"""
"""验证IP地址格式"""
try:
ipaddress.ip_address(ip)
return True
@@ -66,32 +57,86 @@ 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 offline_mode(app: P2PChatApp):
"""离线模式:加密和解密消息"""
print("\n" + "="*40)
print(" 离线模式(消息加密/解密)")
print("="*40)
print("输入 'q' 或 'exit' 可返回主菜单\n")
while True:
print("\n请选择操作:")
print("1. 加密消息(输出Base64密文)")
print("2. 解密消息(输入Base64密文)")
print("0. 返回主菜单")
choice = get_input("请输入选项 (0/1/2): ", lambda x: x in ('0', '1', '2'))
if choice is None or choice == "0":
return
if choice == "1":
print("\n【加密消息】")
message = get_input("请输入要加密的消息: ")
if message is None:
continue
try:
# 加密消息
ciphertext = app.encryptor.encrypt(message)
# 转换为Base64字符串
base64_cipher = base64.b64encode(ciphertext).decode('utf-8')
print("\n" + "="*40)
print("加密成功!Base64格式密文:")
print("="*40)
print(base64_cipher)
print("="*40)
print("(请复制此密文并通过其他方式发送给接收方)")
except Exception as e:
print(f"❌ 加密失败: {e}")
elif choice == "2":
print("\n【解密消息】")
base64_input = get_input("请输入Base64格式的密文: ")
if base64_input is None:
continue
try:
# 解码Base64字符串
ciphertext = base64.b64decode(base64_input)
# 解密消息
message = app.encryptor.decrypt(ciphertext)
print("\n" + "="*40)
print("解密成功!原始消息:")
print("="*40)
print(message)
print("="*40)
except Exception as e:
print(f"❌ 解密失败: {e}")
print("可能原因:")
print("1. 使用了错误的密钥对")
print("2. 输入了无效的Base64格式")
print("3. 数据损坏")
def main():
# Windows环境下添加DLL搜索路径
# 添加DLL搜索路径(仅限Windows)
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):
@@ -102,14 +147,12 @@ def main():
# 验证密钥路径
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'],
@@ -120,15 +163,15 @@ def main():
print("❌ 程序初始化失败,请检查日志")
sys.exit(1)
# 主循环
while True:
print("\n请选择模式:")
print("1. 发送消息(持续聊天模式)")
print("2. 监听消息")
print("0. 退出程序")
print("3. 离线模式(消息加密/解密)")
choice = get_input("请输入选项 (0/1/2): ", lambda x: x in ('0', '1', '2'))
if choice is None: # 用户选择退出
choice = get_input("请输入选项 (0/1/2/3): ", lambda x: x in ('0', '1', '2', '3'))
if choice is None:
break
if choice == "0":
@@ -137,7 +180,6 @@ def main():
elif choice == "1":
print("\n【发送模式】")
# 获取目标IP和端口
target_ip = get_input(
"请输入目标IP地址: ",
is_valid_ip,
@@ -179,6 +221,9 @@ def main():
logger.error(f"监听模式错误: {e}")
print("❌ 监听模式出现错误,请检查日志")
elif choice == "3":
offline_mode(app)
if __name__ == "__main__":
try:
main()