上传文件至 /
This commit is contained in:
@@ -0,0 +1,56 @@
|
|||||||
|
# cli/app.py
|
||||||
|
|
||||||
|
import os
|
||||||
|
from core.encryption import RSAEncryptor
|
||||||
|
from core.transport import UDPTransport
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
self.encryptor = RSAEncryptor(friend_public_key_path, my_private_key_path, my_public_key_path)
|
||||||
|
|
||||||
|
def send_mode(self, target_ip: str, target_port: int):
|
||||||
|
transport = UDPTransport()
|
||||||
|
print(f"\n[>] 已连接到 {target_ip}:{target_port},输入消息内容直接发送(输入'q'退出)")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
message = input(">>> ").strip()
|
||||||
|
if message.lower() in ('q', 'exit'):
|
||||||
|
print("[>] 退出发送模式")
|
||||||
|
break
|
||||||
|
if not message:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
ciphertext = self.encryptor.encrypt(message)
|
||||||
|
transport.send(ciphertext, target_ip, target_port)
|
||||||
|
print(f"[√] 消息已发送")
|
||||||
|
except ValueError as e:
|
||||||
|
print(f"[!] 加密失败:{e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[!] 发送失败:{e}")
|
||||||
|
|
||||||
|
transport.close()
|
||||||
|
|
||||||
|
def listen_mode(self, listen_port: int):
|
||||||
|
print(f"[~] 正在监听 UDP 端口 {listen_port}(IPv4/IPv6 双栈支持)")
|
||||||
|
transport = UDPTransport(bind_port=listen_port)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
data, sender_ip, sender_port = transport.receive()
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
message = self.encryptor.decrypt(data)
|
||||||
|
print(f"\n[<] 来自 {sender_ip}:{sender_port} 的消息:{message}")
|
||||||
|
print(">>> ", end="", flush=True) # 保持输入提示符
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n[!] 解密失败:{e}")
|
||||||
|
print(">>> ", end="", flush=True)
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
import sys
|
||||||
|
import ipaddress
|
||||||
|
import os
|
||||||
|
from cli.app import P2PChatApp
|
||||||
|
|
||||||
|
# 获取当前目录
|
||||||
|
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')
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_ip(ip: str) -> bool:
|
||||||
|
try:
|
||||||
|
ipaddress.ip_address(ip)
|
||||||
|
return True
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_port(port_str: str) -> bool:
|
||||||
|
if not port_str.isdigit():
|
||||||
|
return False
|
||||||
|
port = int(port_str)
|
||||||
|
return 1 <= port <= 65535
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("欢迎使用P2P加密聊天系统")
|
||||||
|
print("输入 'q' 或 'exit' 退出程序")
|
||||||
|
|
||||||
|
# 创建P2PChatApp实例,传入公私钥路径
|
||||||
|
app = P2PChatApp(friend_public_key_path, my_private_key_path, my_public_key_path)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
print("\n请选择模式:")
|
||||||
|
print("1. 发送消息(持续模式)")
|
||||||
|
print("2. 监听消息")
|
||||||
|
print("0. 退出")
|
||||||
|
|
||||||
|
choice = input("输入选项(0/1/2): ").strip().lower()
|
||||||
|
if choice in ("0", "q", "exit"):
|
||||||
|
print("再见!退出程序")
|
||||||
|
break
|
||||||
|
|
||||||
|
elif choice == "1":
|
||||||
|
# 获取目标IP和端口
|
||||||
|
while True:
|
||||||
|
target_ip = input("请输入目标IP地址: ").strip()
|
||||||
|
if target_ip.lower() in ("q", "exit"):
|
||||||
|
break
|
||||||
|
if not is_valid_ip(target_ip):
|
||||||
|
print("❌ IP格式错误,请重新输入")
|
||||||
|
continue
|
||||||
|
|
||||||
|
while True:
|
||||||
|
target_port = input("请输入目标端口(1-65535): ").strip()
|
||||||
|
if target_port.lower() in ("q", "exit"):
|
||||||
|
break
|
||||||
|
if not is_valid_port(target_port):
|
||||||
|
print("❌ 端口无效,请输入1-65535的数字")
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
|
||||||
|
if target_port.lower() in ("q", "exit"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 进入持续发送模式
|
||||||
|
app.send_mode(target_ip, int(target_port))
|
||||||
|
break # 发送循环结束后回到主菜单
|
||||||
|
|
||||||
|
elif choice == "2":
|
||||||
|
while True:
|
||||||
|
listen_port = input("请输入监听端口(1-65535): ").strip()
|
||||||
|
if listen_port.lower() in ("q", "exit"):
|
||||||
|
break
|
||||||
|
if not is_valid_port(listen_port):
|
||||||
|
print("❌ 端口无效,请输入1-65535的数字")
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
|
||||||
|
if listen_port.lower() in ("q", "exit"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
print("开始监听,按 Ctrl+C 停止")
|
||||||
|
try:
|
||||||
|
app.listen_mode(int(listen_port))
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n监听已停止")
|
||||||
|
|
||||||
|
else:
|
||||||
|
print("❌ 无效选项,请重新输入")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from cryptography.hazmat.primitives import serialization, hashes
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||||
|
|
||||||
|
|
||||||
|
class RSAEncryptor:
|
||||||
|
def __init__(self, friend_public_key_path: str, my_private_key_path: str, my_public_key_path: str):
|
||||||
|
# 加载朋友的公钥
|
||||||
|
with open(friend_public_key_path, "rb") as f:
|
||||||
|
self.friend_public_key = serialization.load_pem_public_key(f.read())
|
||||||
|
|
||||||
|
# 加载自己的私钥
|
||||||
|
with open(my_private_key_path, "rb") as f:
|
||||||
|
self.my_private_key = serialization.load_pem_private_key(f.read(), password=None)
|
||||||
|
|
||||||
|
# 加载自己的公钥(这个部分是可选的,具体依赖于你的需求)
|
||||||
|
with open(my_public_key_path, "rb") as f:
|
||||||
|
self.my_public_key = serialization.load_pem_public_key(f.read())
|
||||||
|
|
||||||
|
def encrypt(self, message: str) -> bytes:
|
||||||
|
message_bytes = message.encode("utf-8")
|
||||||
|
max_length = self.friend_public_key.key_size // 8 - 2 * hashes.SHA256().digest_size - 2
|
||||||
|
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()), algorithm=hashes.SHA256(), label=None),
|
||||||
|
)
|
||||||
|
return ciphertext
|
||||||
|
|
||||||
|
def decrypt(self, ciphertext: bytes) -> str:
|
||||||
|
# 使用自己的私钥解密消息
|
||||||
|
plaintext = self.my_private_key.decrypt(
|
||||||
|
ciphertext,
|
||||||
|
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
|
||||||
|
)
|
||||||
|
return plaintext.decode("utf-8")
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# 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()
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# core/transport.py
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import ipaddress
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
|
||||||
|
def ipv4_to_ipv6_mapped(ipv4_addr: str) -> str:
|
||||||
|
try:
|
||||||
|
ip_obj = ipaddress.ip_address(ipv4_addr)
|
||||||
|
if ip_obj.version == 4:
|
||||||
|
return "::ffff:" + ipv4_addr
|
||||||
|
return ipv4_addr
|
||||||
|
except ValueError:
|
||||||
|
return ipv4_addr
|
||||||
|
|
||||||
|
|
||||||
|
class UDPTransport:
|
||||||
|
def __init__(self, bind_ip: str = '', bind_port: int = 0):
|
||||||
|
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
|
||||||
|
self.sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
|
||||||
|
self.sock.bind((bind_ip, bind_port))
|
||||||
|
self.sock.settimeout(5.0)
|
||||||
|
|
||||||
|
def send(self, data: bytes, target_ip: str, target_port: int):
|
||||||
|
target_ip_v6 = ipv4_to_ipv6_mapped(target_ip)
|
||||||
|
addrinfo = socket.getaddrinfo(target_ip_v6, target_port, socket.AF_INET6, socket.SOCK_DGRAM)
|
||||||
|
if not addrinfo:
|
||||||
|
raise ValueError(f"目标地址解析失败: {target_ip}")
|
||||||
|
af, socktype, proto, canonname, sa = addrinfo[0]
|
||||||
|
self.sock.sendto(data, sa)
|
||||||
|
|
||||||
|
def receive(self, timeout: float = 5.0) -> Tuple[bytes, str, int]:
|
||||||
|
self.sock.settimeout(timeout)
|
||||||
|
try:
|
||||||
|
data, addr = self.sock.recvfrom(4096)
|
||||||
|
ip, port = addr[0], addr[1]
|
||||||
|
return data, ip, port
|
||||||
|
except socket.timeout:
|
||||||
|
return b'', '', -1
|
||||||
|
except ConnectionResetError:
|
||||||
|
return b'', '', -1
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.sock.close()
|
||||||
Reference in New Issue
Block a user