diff --git a/.gitignore b/.gitignore index 1e6c292..cf2b89c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ example.py ReEncrypt.py src/temp_message_file src/temp_key_file +src/client.db diff --git a/README_en.md b/README_en.md index 46ccff6..9820a90 100644 --- a/README_en.md +++ b/README_en.md @@ -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 diff --git a/basedockerfile b/basedockerfile index 622815f..960c6ca 100644 --- a/basedockerfile +++ b/basedockerfile @@ -1,6 +1,8 @@ FROM python:3.11 -COPY src /app +COPY requirements.txt /app/ + +COPY lib/* /lib/ WORKDIR /app diff --git a/src/README_app.md b/doc/README_app.md similarity index 100% rename from src/README_app.md rename to doc/README_app.md diff --git a/doc/README_app_en.md b/doc/README_app_en.md new file mode 100644 index 0000000..174da99 --- /dev/null +++ b/doc/README_app_en.md @@ -0,0 +1,7 @@ +# APP Doc + +## Client router + +/request_node +get method +pr diff --git a/src/README_tpre.md b/doc/README_tpre.md similarity index 100% rename from src/README_tpre.md rename to doc/README_tpre.md diff --git a/src/README_tpre_en.md b/doc/README_tpre_en.md similarity index 100% rename from src/README_tpre_en.md rename to doc/README_tpre_en.md diff --git a/requirements.txt b/requirements.txt index 049ec0e..9551179 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,3 @@ -gmssl-python \ No newline at end of file +gmssl-python +fastapi +uvicorn \ No newline at end of file diff --git a/src/README_app_en.md b/src/README_app_en.md deleted file mode 100644 index e69de29..0000000 diff --git a/src/client.ini b/src/client.ini new file mode 100644 index 0000000..04c5027 --- /dev/null +++ b/src/client.ini @@ -0,0 +1,3 @@ +[settings] +server_address = "127.0.0.1:8000" +version = 1.0 diff --git a/src/client.py b/src/client.py index e69de29..28e4f69 100644 --- a/src/client.py +++ b/src/client.py @@ -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) diff --git a/src/demo.py b/src/demo.py index f68dc8a..b8a2b46 100644 --- a/src/demo.py +++ b/src/demo.py @@ -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) diff --git a/test.py b/test.py deleted file mode 100644 index 3b4e363..0000000 --- a/test.py +++ /dev/null @@ -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()) \ No newline at end of file