Compare commits
15
Commits
10e916a2af
...
v1.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
860ffa2846 | ||
|
|
66966dd113 | ||
|
|
ee45a2c081 | ||
|
|
f4e32cdbfc | ||
|
|
900d4fba30 | ||
|
|
f1938cfbe8 | ||
|
|
6f07c1f6e7 | ||
|
|
4251eb6713 | ||
|
|
ae89ae4bb7 | ||
|
|
0044638a40 | ||
|
|
7e4722c9e5 | ||
|
|
5dc66d22bd | ||
|
|
9ec475e5e8 | ||
|
|
4f307eadc9 | ||
|
|
505ad8b015 |
@@ -1,2 +1,7 @@
|
||||
# RSA-Chat
|
||||
|
||||
## 使用方法
|
||||
需要使用openssl进行密钥生成,私钥保存为local.key放置于与主程序相同目录的位置。
|
||||
通信双方请提前交换公钥,程序不会传输公钥。
|
||||
程序使用UDP传输数据,并且使用点对点连接。如果在nat后需要使用内网穿透。
|
||||
## 待办
|
||||
传输文件
|
||||
Executable
BIN
Binary file not shown.
@@ -1,2 +1,6 @@
|
||||
C++ version:
|
||||
openssl 3.0 or later
|
||||
python version:
|
||||
Python 3.8 or later
|
||||
cryptography >= 38.0.0
|
||||
pyOpenSSL >= 22.0.0
|
||||
Executable
BIN
Binary file not shown.
+87
-38
@@ -1,9 +1,19 @@
|
||||
#include <iostream>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <arpa/inet.h>
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <windows.h>
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
#else
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#define SOCKET int
|
||||
#define INVALID_SOCKET (~0)
|
||||
#define closesocket close
|
||||
#endif
|
||||
#include <string>
|
||||
#include <netdb.h>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <openssl/rsa.h>
|
||||
@@ -15,23 +25,39 @@
|
||||
#include <openssl/err.h>
|
||||
|
||||
std::atomic<bool> stop_flag(false);
|
||||
std::atomic<bool> waiting(false);
|
||||
bool listen_mode=true,send_mode=true;
|
||||
|
||||
void init_network() {
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
|
||||
fprintf(stderr, "WSAStartup failed: %d\n", WSAGetLastError());
|
||||
exit(1);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void cleanup_network() {
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
void receive(int sockfd,EVP_PKEY *key,addrinfo* result){
|
||||
if(sockfd<0){
|
||||
if(sockfd<0||!listen_mode){
|
||||
return;
|
||||
}
|
||||
char buffer[BUFFER_SIZE]={0};
|
||||
sockaddr_storage clientAddr{};
|
||||
socklen_t addrLen = sizeof(clientAddr);
|
||||
while(!stop_flag){
|
||||
while(waiting){
|
||||
sleep(1);
|
||||
}
|
||||
ssize_t received = recvfrom(sockfd, buffer, sizeof(buffer), 0,(sockaddr*)&clientAddr, &addrLen);
|
||||
ssize_t received = recvfrom(sockfd, buffer, sizeof(buffer), 0,NULL, NULL);
|
||||
char output[received];
|
||||
int size = text_decrypt(key,buffer,output);
|
||||
std::cout.write(output,size);std::cout<<"$ ";
|
||||
if(size < 0){
|
||||
return;
|
||||
}
|
||||
std::cout << "\033[32m";
|
||||
std::cout.write(output,size);std::cout<<"\033[0m\n";
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -61,7 +87,10 @@ void cutline(char *_p,char **_sto,char _c,char *_o){
|
||||
}
|
||||
|
||||
int main(int argn,char* argc[]){
|
||||
ERR_print_errors_fp(stderr);
|
||||
#ifdef _WIN32
|
||||
SetConsoleOutputCP(CP_UTF8);
|
||||
SetConsoleCP(CP_UTF8);
|
||||
#endif
|
||||
if(argn==1){
|
||||
std::cout << "Useage: " << argc[0] << " <port> <peer public key file path>" << std::endl;
|
||||
std::cout << "Useage: " << argc[0] << " --offline <peer public key file path>" << std::endl;
|
||||
@@ -69,21 +98,28 @@ int main(int argn,char* argc[]){
|
||||
}
|
||||
int peer_bits,local_bits;
|
||||
std::fstream fio;
|
||||
char peer_c[BUFFER_SIZE],local_c[BUFFER_SIZE];
|
||||
char peer_c[BUFFER_SIZE]={0},local_c[BUFFER_SIZE]={0};
|
||||
EVP_PKEY* peer_key = EVP_PKEY_new();EVP_PKEY* local_key = EVP_PKEY_new();
|
||||
fio.open(argc[2],std::ios::in);
|
||||
if(!fio.is_open()){
|
||||
fio.close();
|
||||
send_mode=false;
|
||||
std::cout << "Peer public key read failed ,send mode will be disabled.\n";
|
||||
}else{
|
||||
fio.read(peer_c,BUFFER_SIZE);
|
||||
fio.close();
|
||||
EVP_PKEY* peer_key = EVP_PKEY_new();
|
||||
{
|
||||
BIO* peer_bio = BIO_new_mem_buf(peer_c,strlen(peer_c));
|
||||
PEM_read_bio_PUBKEY(peer_bio,&peer_key,nullptr,nullptr);
|
||||
peer_bits = EVP_PKEY_bits(peer_key);
|
||||
}
|
||||
fio.open("/home/sakitsuki_asahi/ssl/rsa/local.key",std::ios::in);
|
||||
if(!fio.is_open()){
|
||||
fio.close();
|
||||
listen_mode=false;
|
||||
std::cout << "Local private key read failed ,listen/receive mode will be disabled.\n";
|
||||
}else{
|
||||
fio.read(local_c,BUFFER_SIZE);
|
||||
fio.close();
|
||||
EVP_PKEY* local_key = EVP_PKEY_new();
|
||||
{
|
||||
BIO* local_bio = BIO_new_mem_buf(local_c,strlen(local_c));
|
||||
PEM_read_bio_PrivateKey(local_bio,&local_key,nullptr,nullptr);
|
||||
local_bits = EVP_PKEY_bits(local_key);
|
||||
@@ -91,15 +127,17 @@ int main(int argn,char* argc[]){
|
||||
int sockfd = -1;
|
||||
char buffer[BUFFER_SIZE];addrinfo* result;
|
||||
if(strcmp(argc[1],"--offline")!=0){
|
||||
init_network();
|
||||
sockfd = socket(AF_INET6,SOCK_DGRAM,0);
|
||||
if(sockfd < 0){
|
||||
perror("Socket creation failed");
|
||||
return 1;
|
||||
}
|
||||
int no = 0;
|
||||
if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no))) {
|
||||
if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&no, sizeof(no))) {
|
||||
perror("Setsockopt IPV6_V6ONLY failed");
|
||||
close(sockfd);
|
||||
closesocket(sockfd);
|
||||
cleanup_network();
|
||||
return 1;
|
||||
}
|
||||
if(strlen(argc[1])>6||!full_number(argc[1])){
|
||||
@@ -117,7 +155,8 @@ int main(int argn,char* argc[]){
|
||||
serverAddr.sin6_addr = in6addr_any;
|
||||
if (bind(sockfd, (sockaddr*)&serverAddr, sizeof(serverAddr))) {
|
||||
perror("bind failed");
|
||||
close(sockfd);
|
||||
closesocket(sockfd);
|
||||
cleanup_network();
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -126,16 +165,11 @@ int main(int argn,char* argc[]){
|
||||
hints.ai_family = AF_UNSPEC; // 接受IPv4/IPv6
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
std::cout << "UDP socket opened on port " << port << "\n";
|
||||
std::cout << "Please enter <remote IP> <PORT>:\n$ ";
|
||||
if(send_mode){
|
||||
std::cout << "Please enter <remote IP> <PORT>:\n";
|
||||
retry:
|
||||
memset(buffer,0,strlen(buffer));
|
||||
std::cin.getline(buffer,50);
|
||||
if(buffer=="exit"){
|
||||
close(sockfd);
|
||||
EVP_PKEY_free(local_key);
|
||||
EVP_PKEY_free(peer_key);
|
||||
return 0;
|
||||
}
|
||||
char *tmp;
|
||||
char cmd[50]={0};
|
||||
cutline(buffer,&tmp,' ',cmd);
|
||||
@@ -146,9 +180,9 @@ int main(int argn,char* argc[]){
|
||||
}
|
||||
memset(buffer,0,BUFFER_SIZE);
|
||||
}
|
||||
std::thread t(receive,sockfd,local_key,result);
|
||||
}
|
||||
std::thread t(receive, sockfd, local_key, result);
|
||||
while(true){
|
||||
std::cout << "$ ";
|
||||
char user_input[2048];
|
||||
std::cin.getline(user_input,2048);
|
||||
char cmd[2048];
|
||||
@@ -161,7 +195,12 @@ int main(int argn,char* argc[]){
|
||||
std::cout << " help/h/? | Show this page.\n";
|
||||
}
|
||||
if(strcmp(cmd,"s")==0||strcmp(cmd,"send")==0){
|
||||
cutline(cmdcut,&cmdcut,' ',cmd);
|
||||
memset(cmd,0,sizeof(cmd));
|
||||
memcpy(cmd,cmdcut,strlen(cmdcut));
|
||||
if(!send_mode){
|
||||
std::cout << "Send mode is disabled\n";
|
||||
continue;
|
||||
}
|
||||
if(strlen(cmd)>(peer_bits/8-48)){
|
||||
std::cerr << "Text too long for key of peer.\n";
|
||||
continue;
|
||||
@@ -181,11 +220,14 @@ int main(int argn,char* argc[]){
|
||||
if (sent < 0){
|
||||
perror("sendto failed");
|
||||
}
|
||||
waiting=true;
|
||||
memset(buffer,0,sizeof(buffer));
|
||||
}
|
||||
}
|
||||
if(strcmp(cmd,"r")==0||strcmp(cmd,"recv")==0){
|
||||
if(!listen_mode){
|
||||
std::cout << "Recv mode is disabled\n";
|
||||
continue;
|
||||
}
|
||||
if(sockfd>0){
|
||||
std::cout << cmd << " in online mode is disabled.\n";
|
||||
continue;
|
||||
@@ -197,13 +239,20 @@ int main(int argn,char* argc[]){
|
||||
std::cout.write(buffer,size);
|
||||
}
|
||||
if(strcmp(cmd,"exit")==0||strcmp(cmd,"q")==0){
|
||||
break;
|
||||
}
|
||||
}
|
||||
close(sockfd);
|
||||
stop_flag = true;
|
||||
closesocket(sockfd);
|
||||
cleanup_network();
|
||||
EVP_PKEY_free(local_key);
|
||||
EVP_PKEY_free(peer_key);
|
||||
t.detach();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
stop_flag = true;
|
||||
t.join();
|
||||
closesocket(sockfd);
|
||||
cleanup_network();
|
||||
EVP_PKEY_free(local_key);
|
||||
EVP_PKEY_free(peer_key);
|
||||
t.detach();
|
||||
return 0;
|
||||
}
|
||||
@@ -7,15 +7,26 @@
|
||||
|
||||
int text_encrypt(EVP_PKEY* key,char *_i,char *_o){
|
||||
EVP_PKEY_CTX* key_ctx = EVP_PKEY_CTX_new(key, nullptr);
|
||||
if(key_ctx==NULL){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
EVP_PKEY_encrypt_init(key_ctx);
|
||||
EVP_PKEY_CTX_set_rsa_padding(key_ctx, PADDING_METHOD);
|
||||
EVP_PKEY_CTX_set_rsa_oaep_md(key_ctx, EVP_sha256());
|
||||
EVP_PKEY_CTX_set_rsa_mgf1_md(key_ctx, EVP_sha256());
|
||||
size_t enc;
|
||||
int stat = EVP_PKEY_encrypt(key_ctx,nullptr,&enc,(const unsigned char *)_i,strlen(_i));
|
||||
if(stat!=1){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
stat = EVP_PKEY_encrypt(key_ctx,(unsigned char *)_o,&enc,(const unsigned char *)_i,strlen(_i));
|
||||
if(stat!=1){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
return enc;
|
||||
@@ -23,15 +34,26 @@ int text_encrypt(EVP_PKEY* key,char *_i,char *_o){
|
||||
|
||||
int text_decrypt(EVP_PKEY* key,char *_i,char *_o){
|
||||
EVP_PKEY_CTX* key_ctx = EVP_PKEY_CTX_new(key, nullptr);
|
||||
if(key_ctx==NULL){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
EVP_PKEY_decrypt_init(key_ctx);
|
||||
EVP_PKEY_CTX_set_rsa_padding(key_ctx, PADDING_METHOD);
|
||||
EVP_PKEY_CTX_set_rsa_oaep_md(key_ctx, EVP_sha256());
|
||||
EVP_PKEY_CTX_set_rsa_mgf1_md(key_ctx, EVP_sha256());
|
||||
size_t dec;
|
||||
int stat = EVP_PKEY_decrypt(key_ctx,nullptr,&dec,(const unsigned char *)_i,BUFFER_SIZE);
|
||||
if(stat!=1){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
stat = EVP_PKEY_decrypt(key_ctx,(unsigned char *)_o,&dec,(const unsigned char *)_i,dec);
|
||||
if(stat!=1){
|
||||
ERR_print_errors_fp(stderr);
|
||||
ERR_clear_error();
|
||||
return -1;
|
||||
}
|
||||
return dec;
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,98 @@
|
||||
# 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()
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
# cli_shell.py
|
||||
|
||||
import sys
|
||||
import ipaddress
|
||||
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 validate_paths():
|
||||
"""验证密钥文件路径是否存在"""
|
||||
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')
|
||||
}
|
||||
|
||||
missing = [name for name, path in required_paths.items() if not os.path.exists(path)]
|
||||
if missing:
|
||||
logger.error(f"缺少必要的密钥文件: {', '.join(missing)}")
|
||||
print(f"❌ 错误:缺少密钥文件,请检查以下路径是否存在:")
|
||||
for name in missing:
|
||||
print(f" - {required_paths[name]}")
|
||||
sys.exit(1)
|
||||
return required_paths
|
||||
|
||||
def is_valid_ip(ip: str) -> bool:
|
||||
"""验证IP地址格式"""
|
||||
try:
|
||||
ipaddress.ip_address(ip)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
def is_valid_port(port: str) -> bool:
|
||||
"""验证端口号有效性"""
|
||||
return port.isdigit() and 1 <= int(port) <= 65535
|
||||
|
||||
def get_input(prompt: str, validator=None, error_msg="❌ 输入无效"):
|
||||
"""获取用户输入并进行验证"""
|
||||
while True:
|
||||
user_input = input(prompt).strip()
|
||||
if user_input.lower() in ('q', 'exit'):
|
||||
return None
|
||||
|
||||
if validator and not validator(user_input):
|
||||
print(error_msg)
|
||||
continue
|
||||
|
||||
return user_input
|
||||
|
||||
def main():
|
||||
# 验证密钥路径
|
||||
paths = validate_paths()
|
||||
|
||||
print("\n" + "="*40)
|
||||
print(" 欢迎使用P2P加密聊天系统 (PKCS1 v1.5)")
|
||||
print("="*40)
|
||||
print("输入 'q' 或 'exit' 可随时退出当前操作\n")
|
||||
|
||||
try:
|
||||
app = P2PChatApp(
|
||||
paths['friend_public'],
|
||||
paths['my_private'],
|
||||
paths['my_public']
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"初始化失败: {e}")
|
||||
print("❌ 程序初始化失败,请检查日志")
|
||||
sys.exit(1)
|
||||
|
||||
while True:
|
||||
print("\n请选择模式:")
|
||||
print("1. 发送消息(持续聊天模式)")
|
||||
print("2. 监听消息")
|
||||
print("0. 退出程序")
|
||||
|
||||
choice = get_input("请输入选项 (0/1/2): ", lambda x: x in ('0', '1', '2'))
|
||||
if choice is None:
|
||||
break
|
||||
|
||||
if choice == "0":
|
||||
print("\n感谢使用,再见!")
|
||||
break
|
||||
|
||||
elif choice == "1":
|
||||
print("\n【发送模式】")
|
||||
target_ip = get_input(
|
||||
"请输入目标IP地址: ",
|
||||
is_valid_ip,
|
||||
"❌ 无效IP地址格式"
|
||||
)
|
||||
if target_ip is None:
|
||||
continue
|
||||
|
||||
target_port = get_input(
|
||||
"请输入目标端口 (1-65535): ",
|
||||
is_valid_port,
|
||||
"❌ 端口号必须是1-65535的数字"
|
||||
)
|
||||
if target_port is None:
|
||||
continue
|
||||
|
||||
try:
|
||||
app.send_mode(target_ip, int(target_port))
|
||||
except Exception as e:
|
||||
logger.error(f"发送模式错误: {e}")
|
||||
print("❌ 发送模式出现错误,请检查日志")
|
||||
|
||||
elif choice == "2":
|
||||
print("\n【监听模式】")
|
||||
listen_port = get_input(
|
||||
"请输入监听端口 (1-65535): ",
|
||||
is_valid_port,
|
||||
"❌ 端口号必须是1-65535的数字"
|
||||
)
|
||||
if listen_port is None:
|
||||
continue
|
||||
|
||||
print("\n开始监听... (按 Ctrl+C 停止)")
|
||||
try:
|
||||
app.listen_mode(int(listen_port))
|
||||
except KeyboardInterrupt:
|
||||
print("\n🛑 监听已手动停止")
|
||||
except Exception as e:
|
||||
logger.error(f"监听模式错误: {e}")
|
||||
print("❌ 监听模式出现错误,请检查日志")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
print("\n程序已终止")
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
logger.critical(f"未处理的异常: {e}")
|
||||
print("❌ 发生严重错误,程序终止")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,9 @@
|
||||
-----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.
Binary file not shown.
@@ -0,0 +1,80 @@
|
||||
# core/encryption.py
|
||||
|
||||
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
|
||||
|
||||
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填充方案"""
|
||||
try:
|
||||
# 加载朋友的公钥
|
||||
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)
|
||||
|
||||
# 验证密钥是否匹配
|
||||
if self.my_private_key.public_key().public_numbers() != self.friend_public_key.public_numbers():
|
||||
logger.warning("警告:私钥与公钥可能不匹配")
|
||||
|
||||
logger.info(f"RSA加密器初始化成功,密钥长度: {self.friend_public_key.key_size}位")
|
||||
except Exception as e:
|
||||
logger.error(f"密钥加载失败: {e}")
|
||||
raise
|
||||
|
||||
def encrypt(self, message: str) -> bytes:
|
||||
"""使用PKCS1 OAEP加密消息"""
|
||||
try:
|
||||
message_bytes = message.encode("utf-8")
|
||||
max_length = self.friend_public_key.key_size // 8 - 42 # OAEP填充需要更多空间
|
||||
|
||||
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
|
||||
)
|
||||
)
|
||||
logger.debug(f"加密成功,明文长度: {len(message_bytes)}字节,密文长度: {len(ciphertext)}字节")
|
||||
return ciphertext
|
||||
except Exception as e:
|
||||
logger.error(f"加密失败: {e}")
|
||||
raise ValueError("加密失败 - 请检查输入和密钥")
|
||||
|
||||
def decrypt(self, ciphertext: bytes) -> str:
|
||||
"""使用PKCS1 OAEP解密消息"""
|
||||
try:
|
||||
plaintext = self.my_private_key.decrypt(
|
||||
ciphertext,
|
||||
padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None
|
||||
)
|
||||
)
|
||||
|
||||
# 尝试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}"
|
||||
|
||||
except ValueError as e:
|
||||
logger.error(f"解密失败(可能是密钥不匹配): {e}")
|
||||
raise ValueError("解密失败 - 可能是密钥不匹配或数据损坏")
|
||||
except Exception as e:
|
||||
logger.error(f"解密错误: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,83 @@
|
||||
# core/transport.py
|
||||
|
||||
import socket
|
||||
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映射地址"""
|
||||
try:
|
||||
ip_obj = ipaddress.ip_address(ipv4_addr)
|
||||
if ip_obj.version == 4:
|
||||
return "::ffff:" + ipv4_addr
|
||||
return ipv4_addr
|
||||
except ValueError as e:
|
||||
logger.warning(f"IP地址转换失败: {e}")
|
||||
return ipv4_addr # 返回原始地址让上层处理
|
||||
|
||||
class UDPTransport:
|
||||
def __init__(self, bind_ip: str = '', bind_port: int = 0):
|
||||
"""初始化UDP传输层(IPv4/IPv6双栈)"""
|
||||
try:
|
||||
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) # 默认超时5秒
|
||||
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数据包"""
|
||||
try:
|
||||
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}")
|
||||
|
||||
_, _, _, _, sockaddr = addrinfo[0]
|
||||
self.sock.sendto(data, sockaddr)
|
||||
logger.debug(f"Sent {len(data)} bytes to {target_ip}:{target_port}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"发送失败: {e}")
|
||||
return False
|
||||
|
||||
def receive(self, timeout: Optional[float] = None) -> Tuple[bytes, str, int]:
|
||||
"""接收UDP数据包"""
|
||||
if timeout is not None:
|
||||
self.sock.settimeout(timeout)
|
||||
|
||||
try:
|
||||
data, addr = self.sock.recvfrom(4096)
|
||||
ip, port = addr[0], addr[1]
|
||||
logger.debug(f"Received {len(data)} bytes from {ip}:{port}")
|
||||
return data, ip, port
|
||||
except socket.timeout:
|
||||
logger.debug("接收超时")
|
||||
return b'', '', -1
|
||||
except ConnectionResetError:
|
||||
logger.warning("连接被重置(可能对方端口未开放)")
|
||||
return b'', '', -1
|
||||
except Exception as e:
|
||||
logger.error(f"接收错误: {e}")
|
||||
return b'', '', -1
|
||||
|
||||
def close(self):
|
||||
"""关闭socket连接"""
|
||||
try:
|
||||
if hasattr(self, 'sock') and self.sock:
|
||||
self.sock.close()
|
||||
logger.info("Socket已关闭")
|
||||
except Exception as e:
|
||||
logger.error(f"关闭socket时出错: {e}")
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user