forked from sangge/tpre-python
Merge pull request 'main' (#34) from sangge/mimajingsai:main into main
Reviewed-on: dqy/mimajingsai#34
This commit is contained in:
commit
144fabf22c
16
README_en.md
16
README_en.md
@ -7,6 +7,7 @@ This project is designed for the National Cryptography Competition and is implem
|
|||||||
The project uses the Chinese national standard cryptography algorithm to implement distributed proxy re-encryption (TPRE).
|
The project uses the Chinese national standard cryptography algorithm to implement distributed proxy re-encryption (TPRE).
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
.
|
.
|
||||||
├── basedockerfile (being used to build base iamge)
|
├── basedockerfile (being used to build base iamge)
|
||||||
├── dockerfile (being used to build application)
|
├── dockerfile (being used to build application)
|
||||||
@ -22,35 +23,43 @@ The project uses the Chinese national standard cryptography algorithm to impleme
|
|||||||
## Environment Dependencies
|
## Environment Dependencies
|
||||||
|
|
||||||
### Bare mental version(UNTESTED)
|
### Bare mental version(UNTESTED)
|
||||||
|
|
||||||
System requirements:
|
System requirements:
|
||||||
|
|
||||||
- Linux
|
- Linux
|
||||||
- Windows(may need to complie and install gmssl yourself)
|
- Windows(may need to complie and install gmssl yourself)
|
||||||
|
|
||||||
The project relies on the following software:
|
The project relies on the following software:
|
||||||
|
|
||||||
- Python 3.11
|
- Python 3.11
|
||||||
- gmssl
|
- gmssl
|
||||||
- gmssl-python
|
- gmssl-python
|
||||||
|
|
||||||
### Docker version
|
### Docker version
|
||||||
|
|
||||||
docker version:
|
docker version:
|
||||||
|
|
||||||
- Version: 24.0.5
|
- Version: 24.0.5
|
||||||
- API version: 1.43
|
- API version: 1.43
|
||||||
- Go version: go1.20.6
|
- Go version: go1.20.6
|
||||||
|
|
||||||
## Installation Steps
|
## Installation Steps
|
||||||
|
|
||||||
### Pre-installation
|
### Pre-installation
|
||||||
|
|
||||||
This project depends on gmssl, so you need to compile it from source first.
|
This project depends on gmssl, so you need to compile it from source first.
|
||||||
Visit [GmSSL](https://github.com/guanzhi/GmSSL) to learn how to install.
|
Visit [GmSSL](https://github.com/guanzhi/GmSSL) to learn how to install.
|
||||||
|
|
||||||
Then install essential python libs
|
Then install essential python libs
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Docker Installation
|
## Docker Installation
|
||||||
|
|
||||||
### Use base image and build yourself
|
### Use base image and build yourself
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build . -f basedockerfile -t git.mamahaha.work/sangge/tpre:base
|
docker build . -f basedockerfile -t git.mamahaha.work/sangge/tpre:base
|
||||||
docker pull git.mamahaha.work/sangge/tpre:base
|
docker pull git.mamahaha.work/sangge/tpre:base
|
||||||
@ -59,6 +68,7 @@ docker run your_image_name
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Use pre-build image
|
### Use pre-build image
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull git.mamahaha.work/sangge/tpre:latest
|
docker pull git.mamahaha.work/sangge/tpre:latest
|
||||||
docker run git.mamahaha.work/sangge/tpre:latest
|
docker run git.mamahaha.work/sangge/tpre:latest
|
||||||
@ -66,11 +76,11 @@ docker run git.mamahaha.work/sangge/tpre:latest
|
|||||||
|
|
||||||
## Usage Instructions
|
## Usage Instructions
|
||||||
|
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
[TPRE Algorithm Blog Post](https://www.cnblogs.com/pam-sh/p/17364656.html#tprelib%E7%AE%97%E6%B3%95)
|
[TPRE Algorithm Blog Post](https://www.cnblogs.com/pam-sh/p/17364656.html#tprelib%E7%AE%97%E6%B3%95)
|
||||||
[Gmssl-python library](https://github.com/GmSSL/GmSSL-Python)
|
[Gmssl-python library](https://github.com/GmSSL/GmSSL-Python)
|
||||||
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
GNU GENERAL PUBLIC LICENSE v3
|
GNU GENERAL PUBLIC LICENSE v3
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
/request_node
|
/request_node
|
||||||
get method
|
get method
|
||||||
pr
|
|
||||||
|
|
||||||
|
|
||||||
docker run -it -p 8000:8000 -p 8001:8001 -p 8002:8002 -v ~/mimajingsai:/app -e HOST_IP=110.41.130.197 git.mamahaha.work/sangge/tpre:base bash
|
docker run -it -p 8000:8000 -p 8001:8001 -p 8002:8002 -v ~/mimajingsai:/app -e HOST_IP=110.41.130.197 git.mamahaha.work/sangge/tpre:base bash
|
||||||
|
@ -95,6 +95,7 @@ def clean_env():
|
|||||||
with sqlite3.connect("client.db") as db:
|
with sqlite3.connect("client.db") as db:
|
||||||
db.execute("DELETE FROM node")
|
db.execute("DELETE FROM node")
|
||||||
db.execute("DELETE FROM message")
|
db.execute("DELETE FROM message")
|
||||||
|
db.execute("DELETE FROM senderinfo")
|
||||||
db.commit()
|
db.commit()
|
||||||
print("Exit app")
|
print("Exit app")
|
||||||
|
|
||||||
@ -121,8 +122,10 @@ async def receive_messages(message: C):
|
|||||||
return:
|
return:
|
||||||
status_code
|
status_code
|
||||||
"""
|
"""
|
||||||
|
print(f"Received message: {message}")
|
||||||
|
|
||||||
if not message.Tuple or not message.ip:
|
if not message.Tuple or not message.ip:
|
||||||
|
print("Invalid input data received.")
|
||||||
raise HTTPException(status_code=400, detail="Invalid input data")
|
raise HTTPException(status_code=400, detail="Invalid input data")
|
||||||
|
|
||||||
C_capsule, C_ct = message.Tuple
|
C_capsule, C_ct = message.Tuple
|
||||||
@ -144,6 +147,7 @@ async def receive_messages(message: C):
|
|||||||
(bin_C_capsule, str(C_ct), ip),
|
(bin_C_capsule, str(C_ct), ip),
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
print("Data inserted successfully into database.")
|
||||||
check_merge(C_ct, ip)
|
check_merge(C_ct, ip)
|
||||||
return HTTPException(status_code=200, detail="Message received")
|
return HTTPException(status_code=200, detail="Message received")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -230,11 +234,13 @@ async def send_messages(
|
|||||||
for i in range(4):
|
for i in range(4):
|
||||||
id += int(ip_parts[i]) << (24 - (8 * i))
|
id += int(ip_parts[i]) << (24 - (8 * i))
|
||||||
id_list.append(id)
|
id_list.append(id)
|
||||||
|
print(f"Calculated IDs: {id_list}")
|
||||||
# generate rk
|
# generate rk
|
||||||
rk_list = GenerateReKey(sk, pk_B, len(node_ips), shreshold, tuple(id_list)) # type: ignore
|
rk_list = GenerateReKey(sk, pk_B, len(node_ips), shreshold, tuple(id_list)) # type: ignore
|
||||||
|
print(f"Generated ReKey list: {rk_list}")
|
||||||
capsule, ct = Encrypt(pk, message) # type: ignore
|
capsule, ct = Encrypt(pk, message) # type: ignore
|
||||||
# capsule_ct = (capsule, int.from_bytes(ct))
|
# capsule_ct = (capsule, int.from_bytes(ct))
|
||||||
|
print(f"Encrypted message to capsule={capsule}, ct={ct}")
|
||||||
|
|
||||||
for i in range(len(node_ips)):
|
for i in range(len(node_ips)):
|
||||||
url = "http://" + node_ips[i][0] + ":8001" + "/user_src"
|
url = "http://" + node_ips[i][0] + ":8001" + "/user_src"
|
||||||
@ -245,11 +251,15 @@ async def send_messages(
|
|||||||
"ct": int.from_bytes(ct),
|
"ct": int.from_bytes(ct),
|
||||||
"rk": rk_list[i],
|
"rk": rk_list[i],
|
||||||
}
|
}
|
||||||
print(json.dumps(payload))
|
print(f"Sending payload to {url}: {json.dumps(payload)}")
|
||||||
response = requests.post(url, json=payload)
|
response = requests.post(url, json=payload)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
print(f"send to {node_ips[i]} successful")
|
print(f"send to {node_ips[i]} successful")
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f"Failed to send to {node_ips[i]}. Response code: {response.status_code}, Response text: {response.text}"
|
||||||
|
)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
@ -269,6 +279,9 @@ class Request_Message(BaseModel):
|
|||||||
@app.post("/request_message")
|
@app.post("/request_message")
|
||||||
async def request_message(i_m: Request_Message):
|
async def request_message(i_m: Request_Message):
|
||||||
global message, node_response, pk
|
global message, node_response, pk
|
||||||
|
print(
|
||||||
|
f"Function 'request_message' called with: dest_ip={i_m.dest_ip}, message_name={i_m.message_name}"
|
||||||
|
)
|
||||||
dest_ip = i_m.dest_ip
|
dest_ip = i_m.dest_ip
|
||||||
# dest_ip = dest_ip.split(":")[0]
|
# dest_ip = dest_ip.split(":")[0]
|
||||||
message_name = i_m.message_name
|
message_name = i_m.message_name
|
||||||
@ -281,21 +294,25 @@ async def request_message(i_m: Request_Message):
|
|||||||
"source_ip": source_ip,
|
"source_ip": source_ip,
|
||||||
"pk": pk,
|
"pk": pk,
|
||||||
}
|
}
|
||||||
|
print(f"Sending request to {url} with payload: {payload}")
|
||||||
try:
|
try:
|
||||||
response = requests.post(url, json=payload, timeout=1)
|
response = requests.post(url, json=payload, timeout=1)
|
||||||
|
print(f"Response received from {url}: {response.text}")
|
||||||
# print("menxian and pk", response.text)
|
# print("menxian and pk", response.text)
|
||||||
|
|
||||||
except requests.Timeout:
|
except requests.Timeout:
|
||||||
print("can't post")
|
print("Timeout error: can't post to the destination.")
|
||||||
|
# print("can't post")
|
||||||
# content = {"message": "post timeout", "error": str(e)}
|
# content = {"message": "post timeout", "error": str(e)}
|
||||||
# return JSONResponse(content, status_code=400)
|
# return JSONResponse(content, status_code=400)
|
||||||
|
|
||||||
# wait 3s to receive message from nodes
|
# wait 3s to receive message from nodes
|
||||||
for _ in range(10):
|
for _ in range(10):
|
||||||
print("wait:", node_response)
|
print(f"Waiting for node_response... Current value: {node_response}")
|
||||||
|
# print("wait:", node_response)
|
||||||
if node_response:
|
if node_response:
|
||||||
data = message
|
data = message
|
||||||
|
print(f"Node response received with message: {data}")
|
||||||
# reset message and node_response
|
# reset message and node_response
|
||||||
message = b""
|
message = b""
|
||||||
node_response = False
|
node_response = False
|
||||||
@ -303,6 +320,7 @@ async def request_message(i_m: Request_Message):
|
|||||||
# return message to frontend
|
# return message to frontend
|
||||||
return {"message": str(data)}
|
return {"message": str(data)}
|
||||||
await asyncio.sleep(0.2)
|
await asyncio.sleep(0.2)
|
||||||
|
print("Timeout while waiting for node_response.")
|
||||||
content = {"message": "receive timeout"}
|
content = {"message": "receive timeout"}
|
||||||
return JSONResponse(content, status_code=400)
|
return JSONResponse(content, status_code=400)
|
||||||
|
|
||||||
@ -311,14 +329,20 @@ async def request_message(i_m: Request_Message):
|
|||||||
@app.post("/receive_request")
|
@app.post("/receive_request")
|
||||||
async def receive_request(i_m: IP_Message):
|
async def receive_request(i_m: IP_Message):
|
||||||
global pk
|
global pk
|
||||||
|
print(
|
||||||
|
f"Function 'receive_request' called with: dest_ip={i_m.dest_ip}, source_ip={i_m.source_ip}, pk={i_m.pk}"
|
||||||
|
)
|
||||||
source_ip = get_own_ip()
|
source_ip = get_own_ip()
|
||||||
|
print(f"Own IP: {source_ip}")
|
||||||
if source_ip != i_m.dest_ip:
|
if source_ip != i_m.dest_ip:
|
||||||
|
print("Mismatch in destination IP.")
|
||||||
return HTTPException(status_code=400, detail="Wrong ip")
|
return HTTPException(status_code=400, detail="Wrong ip")
|
||||||
dest_ip = i_m.source_ip
|
dest_ip = i_m.source_ip
|
||||||
# threshold = random.randrange(1, 2)
|
# threshold = random.randrange(1, 2)
|
||||||
threshold = 2
|
threshold = 2
|
||||||
own_public_key = pk
|
own_public_key = pk
|
||||||
pk_B = i_m.pk
|
pk_B = i_m.pk
|
||||||
|
print(f"Using own public key: {own_public_key} and received public key: {pk_B}")
|
||||||
|
|
||||||
with sqlite3.connect("client.db") as db:
|
with sqlite3.connect("client.db") as db:
|
||||||
cursor = db.execute(
|
cursor = db.execute(
|
||||||
@ -330,14 +354,18 @@ async def receive_request(i_m: IP_Message):
|
|||||||
(threshold,),
|
(threshold,),
|
||||||
)
|
)
|
||||||
node_ips = cursor.fetchall()
|
node_ips = cursor.fetchall()
|
||||||
|
print(f"Selected node IPs from database: {node_ips}")
|
||||||
|
|
||||||
# message name
|
# message name
|
||||||
|
# message_name = i_m.message_name
|
||||||
|
# message = xxxxx
|
||||||
message = b"hello world" + random.randbytes(8)
|
message = b"hello world" + random.randbytes(8)
|
||||||
|
print(f"Generated message: {message}")
|
||||||
|
|
||||||
# send message to nodes
|
# send message to nodes
|
||||||
await send_messages(tuple(node_ips), message, dest_ip, pk_B, threshold)
|
await send_messages(tuple(node_ips), message, dest_ip, pk_B, threshold)
|
||||||
response = {"threshold": threshold, "public_key": own_public_key}
|
response = {"threshold": threshold, "public_key": own_public_key}
|
||||||
print("###############RESPONSE = ", response)
|
print(f"Sending response: {response}")
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
111
src/demo.py
111
src/demo.py
@ -1,60 +1,71 @@
|
|||||||
from tpre import *
|
from tpre import *
|
||||||
import time
|
import time
|
||||||
|
|
||||||
for N in range(4,21,4):
|
# for T in range(2, 20, 2):
|
||||||
# N = 10
|
N = 10
|
||||||
# T = 5
|
T = N // 2
|
||||||
T = N // 2
|
# print(f"当前门限值: N = {N}, T = {T}")
|
||||||
print(f"当前门限值: N = {N}, T = {T}")
|
|
||||||
|
|
||||||
start_total_time = time.time()
|
start_total_time = time.time()
|
||||||
# 1
|
# 1
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
pk_a, sk_a = GenerateKeyPair()
|
pk_a, sk_a = GenerateKeyPair()
|
||||||
m = b"hello world"
|
# print("pk_a: ", pk_a)
|
||||||
end_time = time.time()
|
# print("sk_a: ", sk_a)
|
||||||
elapsed_time = end_time - start_time
|
end_time = time.time()
|
||||||
print(f"密钥生成运行时间:{elapsed_time}秒")
|
elapsed_time = end_time - start_time
|
||||||
|
# print(f"密钥生成运行时间:{elapsed_time}秒")
|
||||||
|
|
||||||
# 2
|
# 2
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
capsule_ct = Encrypt(pk_a, m)
|
m = b"hello world"
|
||||||
end_time = time.time()
|
capsule_ct = Encrypt(pk_a, m)
|
||||||
elapsed_time = end_time - start_time
|
capsule = capsule_ct[0]
|
||||||
print(f"加密算法运行时间:{elapsed_time}秒")
|
print("check capsule: ", Checkcapsule(capsule))
|
||||||
|
capsule = (capsule[0], capsule[1], -1)
|
||||||
|
print("check capsule: ", Checkcapsule(capsule))
|
||||||
|
# print("capsule_ct: ", capsule_ct)
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time = end_time - start_time
|
||||||
|
# print(f"加密算法运行时间:{elapsed_time}秒")
|
||||||
|
|
||||||
# 3
|
# 3
|
||||||
pk_b, sk_b = GenerateKeyPair()
|
pk_b, sk_b = GenerateKeyPair()
|
||||||
|
|
||||||
|
# 5
|
||||||
|
start_time = time.time()
|
||||||
|
id_tuple = tuple(range(N))
|
||||||
|
rekeys = GenerateReKey(sk_a, pk_b, N, T, id_tuple)
|
||||||
|
# print("rekeys: ", rekeys)
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time = end_time - start_time
|
||||||
|
# print(f"重加密密钥生成算法运行时间:{elapsed_time}秒")
|
||||||
|
|
||||||
# 5
|
# 7
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
id_tuple = tuple(range(N))
|
cfrag_cts = []
|
||||||
rekeys = GenerateReKey(sk_a, pk_b, N, T, id_tuple)
|
|
||||||
end_time = time.time()
|
|
||||||
elapsed_time = end_time - start_time
|
|
||||||
print(f"重加密密钥生成算法运行时间:{elapsed_time}秒")
|
|
||||||
|
|
||||||
# 7
|
for rekey in rekeys:
|
||||||
start_time = time.time()
|
cfrag_ct = ReEncrypt(rekey, capsule_ct)
|
||||||
cfrag_cts = []
|
# cfrag_ct = ReEncrypt(rekeys[0], capsule_ct)
|
||||||
|
cfrag_cts.append(cfrag_ct)
|
||||||
|
# print("cfrag_cts: ", cfrag_cts)
|
||||||
|
end_time = time.time()
|
||||||
|
re_elapsed_time = (end_time - start_time) / len(rekeys)
|
||||||
|
# print(f"重加密算法运行时间:{re_elapsed_time}秒")
|
||||||
|
|
||||||
for rekey in rekeys:
|
# 9
|
||||||
cfrag_ct = ReEncrypt(rekey, capsule_ct)
|
start_time = time.time()
|
||||||
cfrag_cts.append(cfrag_ct)
|
cfrags = mergecfrag(cfrag_cts)
|
||||||
end_time = time.time()
|
# print("cfrags: ", cfrags)
|
||||||
elapsed_time = (end_time - start_time) / len(rekeys)
|
# m = DecryptFrags(sk_b, pk_b, pk_a, cfrags)
|
||||||
print(f"重加密算法运行时间:{elapsed_time}秒")
|
m = DecryptFrags(sk_a, pk_b, pk_a, cfrags)
|
||||||
|
# print("m = ", m)
|
||||||
# 9
|
end_time = time.time()
|
||||||
start_time = time.time()
|
elapsed_time = end_time - start_time
|
||||||
cfrags = mergecfrag(cfrag_cts)
|
end_total_time = time.time()
|
||||||
m = DecryptFrags(sk_b, pk_b, pk_a, cfrags)
|
total_time = end_total_time - start_total_time - re_elapsed_time * len(rekeys)
|
||||||
end_time = time.time()
|
# print(f"解密算法运行时间:{elapsed_time}秒")
|
||||||
elapsed_time = end_time - start_time
|
# print("成功解密:", m)
|
||||||
end_total_time = time.time()
|
# print(f"算法总运行时间:{total_time}秒")
|
||||||
total_time = end_total_time - start_total_time
|
# print()
|
||||||
print(f"解密算法运行时间:{elapsed_time}秒")
|
|
||||||
print("成功解密:", m)
|
|
||||||
print(f"算法总运行时间:{total_time}秒")
|
|
||||||
print()
|
|
||||||
|
93
src/demo2.py
Normal file
93
src/demo2.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
from tpre import *
|
||||||
|
import time
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
# 初始化Excel工作簿和工作表
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "算法性能结果"
|
||||||
|
headers = [
|
||||||
|
"门限值 N",
|
||||||
|
"门限值 T",
|
||||||
|
"密钥生成运行时间",
|
||||||
|
"加密算法运行时间",
|
||||||
|
"重加密密钥生成算法运行时间",
|
||||||
|
"重加密算法运行时间",
|
||||||
|
"解密算法运行时间",
|
||||||
|
"算法总运行时间",
|
||||||
|
]
|
||||||
|
ws.append(headers)
|
||||||
|
|
||||||
|
|
||||||
|
for N in range(4, 21, 2):
|
||||||
|
T = N // 2
|
||||||
|
print(f"当前门限值: N = {N}, T = {T}")
|
||||||
|
|
||||||
|
start_total_time = time.time()
|
||||||
|
# 1
|
||||||
|
start_time = time.time()
|
||||||
|
pk_a, sk_a = GenerateKeyPair()
|
||||||
|
m = b"hello world"
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time_key_gen = end_time - start_time
|
||||||
|
print(f"密钥生成运行时间:{elapsed_time_key_gen}秒")
|
||||||
|
|
||||||
|
# ... [中间代码不变]
|
||||||
|
# 2
|
||||||
|
start_time = time.time()
|
||||||
|
capsule_ct = Encrypt(pk_a, m)
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time_enc = end_time - start_time
|
||||||
|
print(f"加密算法运行时间:{elapsed_time_enc}秒")
|
||||||
|
|
||||||
|
# 3
|
||||||
|
pk_b, sk_b = GenerateKeyPair()
|
||||||
|
|
||||||
|
# 5
|
||||||
|
start_time = time.time()
|
||||||
|
id_tuple = tuple(range(N))
|
||||||
|
rekeys = GenerateReKey(sk_a, pk_b, N, T, id_tuple)
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time_rekey_gen = end_time - start_time
|
||||||
|
print(f"重加密密钥生成算法运行时间:{elapsed_time_rekey_gen}秒")
|
||||||
|
|
||||||
|
# 7
|
||||||
|
start_time = time.time()
|
||||||
|
cfrag_cts = []
|
||||||
|
|
||||||
|
for rekey in rekeys:
|
||||||
|
cfrag_ct = ReEncrypt(rekey, capsule_ct)
|
||||||
|
cfrag_cts.append(cfrag_ct)
|
||||||
|
end_time = time.time()
|
||||||
|
re_elapsed_time = (end_time - start_time) / len(rekeys)
|
||||||
|
print(f"重加密算法运行时间:{re_elapsed_time}秒")
|
||||||
|
|
||||||
|
# 9
|
||||||
|
start_time = time.time()
|
||||||
|
cfrags = mergecfrag(cfrag_cts)
|
||||||
|
m = DecryptFrags(sk_b, pk_b, pk_a, cfrags)
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time_dec = end_time - start_time
|
||||||
|
end_total_time = time.time()
|
||||||
|
total_time = end_total_time - start_total_time - re_elapsed_time * len(rekeys)
|
||||||
|
print(f"解密算法运行时间:{elapsed_time_dec}秒")
|
||||||
|
print("成功解密:", m)
|
||||||
|
print(f"算法总运行时间:{total_time}秒")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 将结果保存到Excel
|
||||||
|
ws.append(
|
||||||
|
[
|
||||||
|
N,
|
||||||
|
T,
|
||||||
|
elapsed_time_key_gen,
|
||||||
|
elapsed_time_enc,
|
||||||
|
elapsed_time_rekey_gen,
|
||||||
|
re_elapsed_time,
|
||||||
|
elapsed_time_dec,
|
||||||
|
total_time,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# 保存Excel文件
|
||||||
|
wb.save("结果.xlsx")
|
12
src/node.py
12
src/node.py
@ -36,6 +36,7 @@ def send_ip():
|
|||||||
# ip = get_local_ip() # type: ignore
|
# ip = get_local_ip() # type: ignore
|
||||||
global id
|
global id
|
||||||
id = requests.get(url, timeout=3)
|
id = requests.get(url, timeout=3)
|
||||||
|
print("中心服务器返回节点ID为: ", id)
|
||||||
|
|
||||||
|
|
||||||
# 用环境变量获取本机ip
|
# 用环境变量获取本机ip
|
||||||
@ -84,7 +85,10 @@ class Req(BaseModel):
|
|||||||
@app.post("/user_src") # 接收用户1发送的信息
|
@app.post("/user_src") # 接收用户1发送的信息
|
||||||
async def user_src(message: Req):
|
async def user_src(message: Req):
|
||||||
global client_ip_src, client_ip_des
|
global client_ip_src, client_ip_des
|
||||||
# kfrag , capsule_ct ,client_ip_src , client_ip_des = json_data[] # 看梁俊勇
|
print(
|
||||||
|
f"Function 'user_src' called with: source_ip={message.source_ip}, dest_ip={message.dest_ip}, capsule={message.capsule}, ct={message.ct}, rk={message.rk}"
|
||||||
|
)
|
||||||
|
# kfrag , capsule_ct ,client_ip_src , client_ip_des = json_data[]
|
||||||
"""
|
"""
|
||||||
payload = {
|
payload = {
|
||||||
"source_ip": local_ip,
|
"source_ip": local_ip,
|
||||||
@ -100,10 +104,12 @@ async def user_src(message: Req):
|
|||||||
ct = message.ct
|
ct = message.ct
|
||||||
capsule_ct = (capsule, ct.to_bytes(32))
|
capsule_ct = (capsule, ct.to_bytes(32))
|
||||||
rk = message.rk
|
rk = message.rk
|
||||||
|
print(f"Computed capsule_ct: {capsule_ct}")
|
||||||
a, b = ReEncrypt(rk, capsule_ct)
|
a, b = ReEncrypt(rk, capsule_ct)
|
||||||
processed_message = (a, int.from_bytes(b))
|
processed_message = (a, int.from_bytes(b))
|
||||||
|
print(f"Re-encrypted message: {processed_message}")
|
||||||
await send_user_des_message(source_ip, dest_ip, processed_message)
|
await send_user_des_message(source_ip, dest_ip, processed_message)
|
||||||
|
print("Message sent to destination user.")
|
||||||
return HTTPException(status_code=200, detail="message recieved")
|
return HTTPException(status_code=200, detail="message recieved")
|
||||||
|
|
||||||
|
|
||||||
@ -120,4 +126,4 @@ async def send_user_des_message(source_ip: str, dest_ip: str, re_message): #
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn # pylint: disable=e0401
|
import uvicorn # pylint: disable=e0401
|
||||||
|
|
||||||
uvicorn.run("node:app", host="0.0.0.0", port=8001, reload=True,log_level="debug")
|
uvicorn.run("node:app", host="0.0.0.0", port=8001, reload=True, log_level="debug")
|
||||||
|
@ -65,9 +65,11 @@ async def get_node(ip: str) -> int:
|
|||||||
ip_int = 0
|
ip_int = 0
|
||||||
for i in range(4):
|
for i in range(4):
|
||||||
ip_int += int(ip_parts[i]) << (24 - (8 * i))
|
ip_int += int(ip_parts[i]) << (24 - (8 * i))
|
||||||
|
print("IP", ip, "对应的ID为", ip_int)
|
||||||
|
|
||||||
# 获取当前时间
|
# 获取当前时间
|
||||||
current_time = int(time.time())
|
current_time = int(time.time())
|
||||||
|
print("当前时间: ", current_time)
|
||||||
|
|
||||||
# 插入数据
|
# 插入数据
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
@ -102,6 +104,7 @@ async def delete_node(ip: str) -> None:
|
|||||||
# 接收节点心跳包
|
# 接收节点心跳包
|
||||||
@app.get("/server/heartbeat")
|
@app.get("/server/heartbeat")
|
||||||
async def receive_heartbeat(ip: str):
|
async def receive_heartbeat(ip: str):
|
||||||
|
print("收到来自", ip, "的心跳包")
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"UPDATE nodes SET last_heartbeat = ? WHERE ip = ?", (time.time(), ip)
|
"UPDATE nodes SET last_heartbeat = ? WHERE ip = ?", (time.time(), ip)
|
||||||
)
|
)
|
||||||
@ -112,7 +115,9 @@ async def receive_heartbeat_internal():
|
|||||||
while 1:
|
while 1:
|
||||||
timeout = 70
|
timeout = 70
|
||||||
# 删除超时的节点
|
# 删除超时的节点
|
||||||
cursor.execute("DELETE FROM nodes WHERE last_heartbeat < ?", (time.time() - timeout,))
|
cursor.execute(
|
||||||
|
"DELETE FROM nodes WHERE last_heartbeat < ?", (time.time() - timeout,)
|
||||||
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
await asyncio.sleep(timeout)
|
await asyncio.sleep(timeout)
|
||||||
|
|
||||||
@ -135,6 +140,8 @@ async def send_nodes_list(count: int) -> list:
|
|||||||
id, ip, last_heartbeat = row
|
id, ip, last_heartbeat = row
|
||||||
nodes_list.append(ip)
|
nodes_list.append(ip)
|
||||||
|
|
||||||
|
print("收到来自客户端的节点列表请求...")
|
||||||
|
print(nodes_list)
|
||||||
return nodes_list
|
return nodes_list
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user