Merge pull request 'main' (#16) from sangge/mimajingsai:main into main

Reviewed-on: dqy/mimajingsai#16
This commit is contained in:
dqy 2023-10-21 15:50:05 +08:00
commit 37bdde3e53
13 changed files with 238 additions and 11 deletions

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ example.py
ReEncrypt.py
src/temp_message_file
src/temp_key_file
src/client.db

View File

@ -10,6 +10,7 @@ The project uses the Chinese national standard cryptography algorithm to impleme
.
├── basedockerfile (being used to build base iamge)
├── dockerfile (being used to build application)
├── doc (development documents)
├── include (gmssl header)
├── lib (gmssl shared object)
├── LICENSE

View File

@ -1,6 +1,8 @@
FROM python:3.11
COPY src /app
COPY requirements.txt /app/
COPY lib/* /lib/
WORKDIR /app

7
doc/README_app_en.md Normal file
View File

@ -0,0 +1,7 @@
# APP Doc
## Client router
/request_node
get method
pr

View File

@ -1 +1,3 @@
gmssl-python
gmssl-python
fastapi
uvicorn

View File

3
src/client.ini Normal file
View File

@ -0,0 +1,3 @@
[settings]
server_address = "127.0.0.1:8000"
version = 1.0

View File

@ -0,0 +1,197 @@
from fastapi import FastAPI, HTTPException
import requests
import os
from typing import Tuple
from tpre import *
import sqlite3
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
init()
yield
clean_env()
app = FastAPI(lifespan=lifespan)
pk = point
sk = int
server_address = str
def init():
global pk, sk, server_address
init_db()
pk, sk = GenerateKeyPair()
init_config()
get_node_list(6, server_address) # type: ignore
def init_db():
with sqlite3.connect("client.db") as db:
# message table
db.execute(
"""
CREATE TABLE IF NOT EXISTS message (
id INTEGER PRIMARY KEY,
capsule TEXT,
ct TEXT,
senderip TEXT
);
"""
)
# node ip table
db.execute(
"""
CREATE TABLE IF NOT EXISTS node (
id INTEGER PRIMARY KEY,
nodeip TEXT
);
"""
)
# sender info table
db.execute(
"""
CREATE TABLE IF NOT EXISTS senderinfo (
id INTEGER PRIMARY KEY,
ip TEXT,
publickey TEXT,
threshold INTEGER
)
"""
)
db.commit()
print("Init Database Successful")
def init_config():
import configparser
global server_address
config = configparser.ConfigParser()
config.read("client.ini")
server_address = config["settings"]["server_address"]
# execute on exit
def clean_env():
print("Exit app")
# main page
@app.get("/")
async def read_root():
return {"message": "Hello, World!"}
# receive messages from node
@app.post("/receive_messages")
async def receive_messages(C: Tuple[capsule, int], ip: str):
"""
receive capsule and ip from nodes
params:
C: capsule and ct
ip: sender ip
return:
status_code
"""
if not C or not ip:
raise HTTPException(status_code=400, detail="Invalid input data")
capsule, ct = C
if not Checkcapsule(capsule):
raise HTTPException(status_code=400, detail="Invalid capsule")
# insert record into database
with sqlite3.connect("message.db") as db:
try:
db.execute(
"INSERT INTO message (capsule_column, ct_column, ip_column) VALUES (?, ?, ?)",
(capsule, ct, ip),
)
db.commit()
await check_merge(db, ct, ip)
return HTTPException(status_code=200, detail="Message received")
except Exception as e:
print(f"Error occurred: {e}")
db.rollback()
return HTTPException(status_code=400, detail="Database error")
# check record count
async def check_merge(db, ct: int, ip: str):
global sk, pk
# Check if the combination of ct_column and ip_column appears more than once.
cursor = db.execute(
"""
SELECT capsule, ct
FROM message
WHERE ct = ? AND senderip = ?
""",
(ct, ip),
)
# [(capsule, ct), ...]
cfrag_cts = cursor.fetchall()
# get N
cursor = db.execute(
"""
SELECT publickey, threshold
FROM senderinfo
WHERE senderip = ?
""",
(ip),
)
result = cursor.fetchall()
pk_sender, T = result[0]
if len(cfrag_cts) >= T:
cfrags = mergecfrag(cfrag_cts)
m = DecryptFrags(sk, pk, pk_sender, cfrags) # type: ignore
# send message to node
@app.post("/send_message")
async def send_message(ip: tuple[str, ...]):
return 0
# request message from others
@app.post("/request_message")
async def request_message(ip):
return 0
# get node list from central server
def get_node_list(count: int, server_addr: str):
url = "http://" + server_addr + "/server/send_nodes_list"
payload = {"count": count}
response = requests.post(url, json=payload)
# Checking the response
if response.status_code == 200:
print("Success get node list")
node_ip = response.text
# insert node ip to database
with sqlite3.connect("client.db") as db:
db.executemany(
"""
INSERT INTO node
nodeip
VALUE (?)
""",
node_ip,
)
db.commit()
print("Success add node ip")
else:
print("Failed:", response.status_code, response.text)
if __name__ == "__main__":
import uvicorn # pylint: disable=e0401
uvicorn.run("client:app", host="0.0.0.0", port=8003)

View File

@ -1,30 +1,50 @@
from tpre import *
import time
# 1
start_time = time.time()
pk_a, sk_a = GenerateKeyPair()
m = b"hello world"
end_time = time.time()
elapsed_time = end_time - start_time
print(f"代码块1运行时间:{elapsed_time}")
# 2
start_time = time.time()
capsule_ct = Encrypt(pk_a, m)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"代码块2运行时间:{elapsed_time}")
# 3
pk_b, sk_b = GenerateKeyPair()
N = 70
T = 49
N = 10
T = 5
# 5
start_time = time.time()
rekeys = GenerateReKey(sk_a, pk_b, N, T)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"代码块5运行时间:{elapsed_time}")
# 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()
elapsed_time = end_time - start_time
print(f"代码块7运行时间:{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 = end_time - start_time
print(f"代码块9运行时间:{elapsed_time}")
print(m)

View File

@ -1,6 +0,0 @@
from gmssl import * #pylint: disable = e0401
sm3 = Sm3() #pylint: disable = e0602
sm3.update(b'abc')
dgst = sm3.digest()
print("sm3('abc') : " + dgst.hex())