add init code

This commit is contained in:
sangge-win 2024-04-09 14:34:58 +08:00
commit f5d515b0f9
12 changed files with 5077 additions and 0 deletions

516
CoreAlgorithm.py Normal file
View File

@ -0,0 +1,516 @@
import random
from collections.abc import Mapping
from encoding import EncodedNumber
from util import invert, powmod, getprimeover
DEFAULT_KEYSIZE = 1024 # 定义默认的二进制数长度
def generate_paillier_keypair(
private_keyring=None, n_length=DEFAULT_KEYSIZE
): # 生成公钥和私钥的函数
# 生成 Paillier 密钥对函数
p = q = n = None # 初始化素数 p, q 和计算结果 n
length = 0 # 初始化计算结果 n 的长度 (即用二进制表示 n 所需要的二进制位数)
while length != n_length: # 循环直至计算结果 n 的长度达到指定长度 n_length
p = getprimeover(n_length // 2) # 随机生成一个 (n_length//2) 长的素数 p
q = p
while q == p:
# 确保 q 与 p 不相等
q = getprimeover(n_length // 2) # 随机生成一个 (n_length//2) 长的素数 q
n = p * q # 计算 n,即两个素数乘积
length = n.bit_length() # 计算 n 的二进制长度
# 创建公钥对象
public_key = PaillierPublicKey(n)
# 创建私钥对象
private_key = PaillierPrivateKey(public_key, p, q)
if private_keyring is not None: # 如果传入了私钥环对象,则将私钥添加到私钥环中
private_keyring.add(private_key)
return public_key, private_key # 返回公钥和私钥
class PaillierPublicKey(object): # 定义公钥类
def __init__(self, n):
self.g = n + 1
self.n = n # 公钥的模数
self.nsquare = n * n # n的平方
self.max_int = n // 3 - 1 # 公钥的一个属性(限制可加密/解密的最大整数值)
def __repr__(self): # 用于打印出该类的对象
public_key_hash = hex(hash(self))[2:]
return "<PaillierPublicKey {}>".format(public_key_hash[:10]) # 返回表示对象的字符串
def __eq__(self, other): # 用于比较两个对象是否相等,并返回比较结果
return self.n == other.n
def __hash__(self): # 用于返回n的Hash值
return hash(self.n)
def get_n_and_g(self): # 获取该公钥的 n 和 g 的值
return self.n, self.g
def raw_encrypt(self, plaintext, r_value=None): # 用于返回加密后的密文,其中r_value可给随机数赋值
if not isinstance(plaintext, int): # 判断plaintext是否是整数
raise TypeError("明文不是整数,而是: %s" % type(plaintext))
if self.n - self.max_int <= plaintext < self.n: # 对于非常大的明文,使用特殊的计算方法进行加密:
neg_plaintext = self.n - plaintext # = abs(plaintext - nsquare)
neg_ciphertext = (self.n * neg_plaintext + 1) % self.nsquare
nude_ciphertext = invert(neg_ciphertext, self.nsquare)
else: # 如果不是非常大的明文:
nude_ciphertext = (
self.n * plaintext + 1
) % self.nsquare # (n + 1)^plaintext = n * plaintext + 1 mod n^2
# 生成一个随机数,其值为r_value。如果r_value没有值,则r随机:
r = r_value or self.get_random_lt_n()
obfuscator = powmod(r, self.n, self.nsquare) # (r ^ n) mod n^2
return (nude_ciphertext * obfuscator) % self.nsquare # 返回加密后的密文
def get_random_lt_n(self): # 返回一个1——n间的随机整数
return random.SystemRandom().randrange(1, self.n)
def encrypt(
self, value, precision=None, r_value=None
): # value表示要加密的值,precision是加密精度,r_value是随机数
# 判断value是否是EncodedNumber类型,如果是则直接赋值给encoding如果不是,则对value进行编码
if isinstance(value, EncodedNumber):
encoding = value
else:
encoding = EncodedNumber.encode(self, value, precision)
return self.encrypt_encoded(encoding, r_value)
def encrypt_encoded(self, encoding, r_value): # 将已编码的数值对象转换为加密后的数值对象,并可以选择进行混淆处理
obfuscator = r_value or 1 # 为随机数r_value,没有则默认为1
ciphertext = self.raw_encrypt(encoding.encoding, r_value=obfuscator)
encrypted_number = EncryptedNumber(self, ciphertext, encoding.exponent)
"""
PS:默认生成情况下不输入随机数r_value的情况下:
encrypt中的随机数r_value为:None
raw_encrypt中的随机数为:1
encrypt_encoded中的随机数为:None
"""
if r_value is None: # 结合上述注释,可知:密文混淆函数是会默认执行的
encrypted_number.obfuscate() # 如果encrypt_encoded没有随机数r_value,则进行密文混淆处理obfuscate()
return encrypted_number
class PaillierPrivateKey(object): # 私钥
def __init__(self, public_key, p, q):
if not p * q == public_key.n: # 如果p * q 不等于 公钥的n,则说明出错
raise ValueError("所给公钥与p,q不匹配")
if p == q: # p,q相同
raise ValueError("p,q不能相同")
self.public_key = public_key
# 给self的p q赋值:
if q < p: # 默认是p 大于等于 q
self.p = q
self.q = p
else:
self.p = p
self.q = q
self.psquare = self.p * self.p
self.qsquare = self.q * self.q
self.p_inverse = invert(self.p, self.q) # 计算p mod q 的乘法逆元
self.hp = self.h_function(self.p, self.psquare) # p mod p方
self.hq = self.h_function(self.q, self.qsquare) # q mod q方
def __repr__(self): # 用于打印出该类的对象
pub_repr = repr(self.public_key)
return "<PaillierPrivateKey for {}>".format(pub_repr)
def decrypt(self, encrypted_number): # 解密密文,并返回明文
# 执行下面这个语句前的类型为EncryptedNumber,执行完毕后类型为EncodedNumber中间会变为int型的ciphertext:
encoded = self.decrypt_encoded(encrypted_number)
return encoded.decode()
def decrypt_encoded(
self, encrypted_number, Encoding=None
): # 用于解密密文并返回解密后的EncodedNumber类型
# 检查输入信息是否是EncryptedNumber参数,如果不是:
if not isinstance(encrypted_number, EncryptedNumber):
raise TypeError(
"参数应该是EncryptedNumber," " 参数不能为: %s" % type(encrypted_number)
)
if self.public_key != encrypted_number.public_key: # 如果公钥与加密数字的公钥不一致
raise ValueError("加密信息不能被不同的公钥进行加密!")
if Encoding is None: # 将Encoding设置为未赋值的EncodedNumber变量
Encoding = EncodedNumber
"""提取 encrypted_number 中的 ciphertext
这里是禁用安全模式,
所以是直接提取ciphertext,
随后调用raw_decrypt函数对ciphertext进行处理:"""
encoded = self.raw_decrypt(encrypted_number.ciphertext(be_secure=False))
return Encoding(self.public_key, encoded, encrypted_number.exponent)
def raw_decrypt(self, ciphertext): # 对密文进行原始解密
if not isinstance(ciphertext, int): # 如果所给的密文不是int型
raise TypeError("密文应该是int型, 而不是: %s" % type(ciphertext))
# 将解密结果存放在p和q中,并将p q进行合并:
decrypt_to_p = (
self.l_function(powmod(ciphertext, self.p - 1, self.psquare), self.p)
* self.hp
% self.p
)
decrypt_to_q = (
self.l_function(powmod(ciphertext, self.q - 1, self.qsquare), self.q)
* self.hq
% self.q
)
return self.crt(decrypt_to_p, decrypt_to_q)
def h_function(self, x, xsquare): # 计算并返回h函数值[用于中国剩余定理]
return invert(self.l_function(powmod(self.public_key.g, x - 1, xsquare), x), x)
def l_function(self, mju, p): # 计算并返回l值算L(μ)
return (mju - 1) // p
def crt(self, mp, mq): # 实现中国剩余定理(Chinese remainder theorem)
u = (mq - mp) * self.p_inverse % self.q
return mp + (u * self.p)
def __eq__(self, other): # 判断两个对象的 q 与 p 是否相等
return self.p == other.p and self.q == other.q
def __hash__(self): # 计算 p 与 q 元组的哈希值
return hash((self.p, self.q))
class PaillierPrivateKeyring(Mapping): # 私钥环类,并继承了Mapping类
def __init__(self, private_keys=None): # 初始化私钥环对象(私钥环列表)
if private_keys is None:
private_keys = []
# 将私钥和公钥进行组合,并存储在私钥环中:
public_keys = [k.public_key for k in private_keys]
self.__keyring = dict(zip(public_keys, private_keys))
def __getitem__(self, key): # 通过公钥,来查找私钥环中对应的私钥
return self.__keyring[key]
def __len__(self): # 存储的私钥数量
return len(self.__keyring)
def __iter__(self): # 遍历私钥环中的公钥
return iter(self.__keyring)
def __delitem__(self, public_key): # 删除与公钥对应的私钥
del self.__keyring[public_key]
def add(self, private_key): # 向私钥环中添加私钥
if not isinstance(private_key, PaillierPrivateKey): # 对要添加的私钥进行判断
raise TypeError("私钥应该是PaillierPrivateKey类型, " "而不是 %s" % type(private_key))
self.__keyring[private_key.public_key] = private_key # 将该公钥和对用的私钥一块儿加入到私钥环中
def decrypt(self, encrypted_number): # 对密文进行解密
relevant_private_key = self.__keyring[
encrypted_number.public_key
] # 在私钥环中获取对应的私钥
return relevant_private_key.decrypt(encrypted_number) # 返回加密结果
class EncryptedNumber(object): # 浮点数或整数的Pailier加密
"""
1. D(E(a) * E(b)) = a + b
2. D(E(a)**b) = a * b
"""
def __init__(self, public_key, ciphertext, exponent=0):
self.public_key = public_key
self.__ciphertext = ciphertext # 密文
self.exponent = exponent # 用于表示指数
self.__is_obfuscated = False # 用于表示数据是否被混淆
if isinstance(self.ciphertext, EncryptedNumber): # 如果密文是EncryptedNumber
raise TypeError("密文必须是int型")
if not isinstance(
self.public_key, PaillierPublicKey
): # 如果公钥不是PaillierPublicKey
raise TypeError("公钥必须是PaillierPublicKey")
def __add__(self, other): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的加法
if isinstance(other, EncryptedNumber):
return self._add_encrypted(other)
elif isinstance(other, EncodedNumber):
return self._add_encoded(other)
else:
return self._add_scalar(other)
def __radd__(self, other): # 反加,处理整数/浮点数与EncryptedNumber之间的加法
return self.__add__(other)
def __mul__(self, other): # 运算符重载,重载为EncryptedNumber与(整数/浮点数)的乘法
# 判断other对象是否是EncryptedNumber,如果是:
if isinstance(other, EncryptedNumber):
raise NotImplementedError("EncryptedNumber 与 EncryptedNumber 之间不能相乘!")
if isinstance(other, EncodedNumber):
encoding = other
else:
encoding = EncodedNumber.encode(self.public_key, other)
product = self._raw_mul(encoding.encoding) # 重新更新乘积
exponent = self.exponent + encoding.exponent # 重新更新指数
return EncryptedNumber(self.public_key, product, exponent)
def __rmul__(self, other): # 反乘,处理整数/浮点数与EncryptedNumber之间的乘法
return self.__mul__(other)
def __sub__(self, other): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的减法
return self + (other * -1)
def __rsub__(self, other): # 处理整数/浮点数与EncryptedNumber之间的减法
return other + (self * -1)
def __truediv__(
self, scalar
): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的除法
return self.__mul__(1 / scalar)
def __invert__(self): # 运算符重载~(对 数 的取反)
return self * (-1)
# def __pow__(self, exponent): # 运算符重载 ** (对密文的幂函数)
# if not isinstance(exponent, int): # 如果输入有问题
# print("指数应输入 整数 标量!")
# else:
# result = self
# for i in [1, exponent]:
# result *= self
# return result
# # 原本的幂运算 ** return self.value ** exponent
def ciphertext(self, be_secure=True): # 用于混淆密文,并返回混淆后的密文
"""
EncryptedNumber类的一个方法ciphertext,用于返回该对象的密文
在Paillier加密中,为了提高计算性能,加法和乘法操作进行了简化,
避免对每个加法和乘法结果进行随机数的加密操作
这样会使得内部计算快速,但会暴露一部分信息
此外,为了保证安全,如果需要与其他人共享密文,应该使用be_secure=True
这样,如果密文还没有被混淆,会调用obfuscate方法对其进行混淆操作
"""
if be_secure and not self.__is_obfuscated: # 如果密文没有被混淆,则进行混淆操作
self.obfuscate()
return self.__ciphertext
def decrease_exponent_to(
self, new_exp
): # 返回一个指数较低但大小相同的数(即返回一个同值的,但指数较低的EncryptedNumber
if new_exp > self.exponent:
raise ValueError("新指数值 %i 应比原指数 %i 小! " % (new_exp, self.exponent))
multiplied = self * pow(EncodedNumber.BASE, self.exponent - new_exp) # 降指数后的乘积
multiplied.exponent = new_exp # 降指数后的新指数
return multiplied
def obfuscate(self): # 混淆密文
r = self.public_key.get_random_lt_n() # 生成一个(1——n)间的随机数r,不 r
r_pow_n = powmod(
r, self.public_key.n, self.public_key.nsquare
) # (r ^ n) mod n^2
self.__ciphertext = (
self.__ciphertext * r_pow_n % self.public_key.nsquare
) # 对原密文进行处理
self.__is_obfuscated = True # 用于判断密文是否被混淆
def _add_scalar(self, scalar): # 执行EncodedNumber与标量(整型/浮点型)相加的操作
encoded = EncodedNumber.encode(
self.public_key, scalar, max_exponent=self.exponent
)
return self._add_encoded(encoded)
def _add_encoded(self, encoded): # 对EncodedNumber与标量encoded加法编码
# 返回 E(a + b)
if self.public_key != encoded.public_key: # 如果公钥与编码公钥不相同
raise ValueError("不能使用不同的公钥,对数字进行编码!")
a, b = self, encoded
# 对指数处理(使指数相同):
if a.exponent > b.exponent:
a = self.decrease_exponent_to(b.exponent)
elif a.exponent < b.exponent:
b = b.decrease_exponent_to(a.exponent)
encrypted_scalar = a.public_key.raw_encrypt(
b.encoding, 1
) # 用公钥加密b.encoding后的标量
sum_ciphertext = a._raw_add(a.ciphertext(False), encrypted_scalar) # 进行相加操作
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
def _add_encrypted(self, other): # 对EncodedNumber与EncodedNumber加法加密
if self.public_key != other.public_key:
raise ValueError("不能使用不同的公钥,对数字进行加密!")
# 对指数处理(使指数相同):
a, b = self, other
if a.exponent > b.exponent:
a = self.decrease_exponent_to(b.exponent)
elif a.exponent < b.exponent:
b = b.decrease_exponent_to(a.exponent)
sum_ciphertext = a._raw_add(a.ciphertext(False), b.ciphertext(False))
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
def _raw_add(self, e_a, e_b): # 对加密后的a,b直接进行相加,并返回未加密的结果
return e_a * e_b % self.public_key.nsquare
def _raw_mul(self, plaintext): # 对密文进行乘法运算,并返回未加密的结果
# 检查乘数是否为int型:
if not isinstance(plaintext, int):
raise TypeError("期望密文应该是int型, 而不是 %s" % type(plaintext))
# 如果乘数是负数,或乘数比公钥的模n大:
if plaintext < 0 or plaintext >= self.public_key.n:
raise ValueError("超出可计算范围: %i" % plaintext)
if self.public_key.n - self.public_key.max_int <= plaintext:
# 如果数据很大,则先反置一下再进行运算:
neg_c = invert(self.ciphertext(False), self.public_key.nsquare)
neg_scalar = self.public_key.n - plaintext
return powmod(neg_c, neg_scalar, self.public_key.nsquare)
else:
return powmod(self.ciphertext(False), plaintext, self.public_key.nsquare)
def increment(self): # 定义自增运算
return self + 1
def decrement(self): # 定义自减运算
return self + 1
def cal_sum(self, *args):
result = 0 # 将初始值设置为0
for i in args:
if not isinstance(i, (int, float, EncryptedNumber)):
raise TypeError("期望密文应该是int/float/EncryptedNumber型, 而不是 %s" % type(i))
if isinstance(i, int or float): # 如果是 int 或 float 明文型,则先将明文加密在进行运算
result += self.public_key.encrypt(i)
else:
result += i # 第一次循环:标量与密文相加;后面的循环,密文与密文相加
return result
def average(self, *args): # 定义求平均值
total_sum = self.cal_sum(
*args
) # 计算总和total是<__main__.EncryptedNumber object at 0x000002AB74FB9850>
# # 如果总数超过了可计算范围
# if total_sum > 91000:
# raise ValueError('超出可计算范围: %i' % total_sum)
count = 0 # 定义count,用来统计参数的个数
for _ in args:
count += 1 # count++
return total_sum / count
def weighted_average(self, *args): # 定义加权平均 def weighted_average(*args):
"""PS:
args[0]: <__main__.EncryptedNumber object at 0x000001F7C1B6A610>
args[1]: 第一个参数
args[2]: 给第一个参数设置的权值
"""
total_weight = sum(args[2::2]) # 计算权值的总和(使用切片操作从参数列表中取出索引为参数权值的元素)
if total_weight != 1:
raise TypeError("加权平均算法的权值设置错误!请重新设置!")
else:
# 计算加权和,其中: for i in range(0, len(args), 2) 表示以2为步长,从0递增,直到 i >= len(args)时:
result = sum(args[i] * args[i + 1] for i in range(1, len(args), 2))
return result
def reset(self): # 定义复位置0运算
zero = self.public_key.encrypt(0) # 用公钥对0进行加密
return zero
def calculate_variance(self, *args): # 定义求方差
mean = self.average(*args) # 均值
count = 0 # 定义count,用来统计参数的个数
for _ in args:
count += 1 # count++
variance = sum((x - mean) ** 2 for x in args) / (count - 1)
return variance
# def IsZero(self): # 判断该数是否为0
# ZERO = self
# zero = ZERO.public_key.encrypt(0) # 用公钥对0进行加密
# flag = False # 用于判断该数是否为0(默认不为0)
#
# if self == zero:
# flag = True
# return flag
# def POW(self, num): # 定义幂运算
# if not isinstance(num, int): # 如果输入有问题
# print("指数应输入 整数 标量!")
# else:
# result = self
# print(num)
# for i in [1, num]:
# result *= self
# return result
# def get_certificate(public_key):
# # 获得公钥的PEM编码的二进制形式
# public_bytes = public_key.public_bytes(
# encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
#
# # 获得数字证书
# cert = (public_bytes, hashlib.sha256(public_bytes).hexdigest()) # 元祖类型
# return cert
if __name__ == "__main__": # 主函数
Public_Key, Private_Key = generate_paillier_keypair() # 随机生成1024长的公钥和私钥
x = 90000.23
y = 90
z = 0.5
x_encrypted = Public_Key.encrypt(x) # 加密后的x
y_encrypted = Public_Key.encrypt(y) # 加密后的y
z_encrypted = Public_Key.encrypt(z) # 加密后的z
t_encrypted = x_encrypted + y_encrypted * 0.5 # 在x,y保密的情况下计算t,得到加密后的t(t_encrypted)
# x_encrypted = x_encrypted.increment() # 自增
# y_encrypted = y_encrypted.decrement() # 自减
# print(x_encrypted != y_encrypted) # 不相等
# print(x_encrypted == y_encrypted) # 相等
# print(Private_Key.decrypt(~x_encrypted) ) # 取反
# total = x_encrypted.cal_sum(x_encrypted, y_encrypted, 0.5) # 求和函数
# print("密文之和为:", Private_Key.decrypt(total))
# avg = x_encrypted.average(y_encrypted, z_encrypted, z_encrypted) # 求平均值函数
# print("密文的平均值为:", Private_Key.decrypt(avg) ) # 只能对0~90090.73的数进行除法运算(除不尽)
# weight_average = x_encrypted.weighted_average(x_encrypted, 0.1, y_encrypted, 0.3, z_encrypted, 0.6) # 加权平均函数
# print("加权平均结果为:", Private_Key.decrypt(weight_average))
# variance = x_encrypted.calculate_variance(x_encrypted, y_encrypted) #求方差
# print("方差为:", Private_Key.decrypt(variance))
# z_encrypted = z_encrypted.reset() # 复位函数
# print("z复位后的结果为:", Private_Key.decrypt(z_encrypted) )
# print(x_encrypted ** x) # 相当于print(x_encrypted.POW(2) )
# print(x_encrypted > y_encrypted)
# print(type(Public_Key))
# print(Public_Key)
print(f"x + y * 0.5的结果是:{Private_Key.decrypt(t_encrypted)}") # 打印出t

295
DataSearch.py Normal file
View File

@ -0,0 +1,295 @@
import re
import pymysql # pylint: disable=e0401 # type: ignore
# 拆分sql对象
def extract_tables(sql_statement):
# 使用正则表达式匹配FROM关键字之后的表名以及逗号分隔的表名
pattern = r"FROM\s+([\w\s,]+)"
matches = re.findall(pattern, sql_statement, re.IGNORECASE)
# 提取逗号分隔的表名,并按逗号进行分割
tabs = re.split(",", matches[0].strip())
# 处理每个表名,去除空格和其他无关字符
cleaned_tables = []
for tab in tabs:
cleaned_tab = tab.strip()
if " " in cleaned_tab:
cleaned_tab = cleaned_tab.split()[0]
cleaned_tables.append(cleaned_tab)
return cleaned_tables # 返回列表
# 拆分sql
def divide_sql(sql):
"""
例如sql = "SELECT a FROM data1, data2, data3 WHERE a = b ORDER BY misc"
拆分原语句
"""
parts = re.split(r"(?i)from\s", sql) # 拆分"from "【无论大小写】
head = parts[0] + "from " # SELECT a FROM
divide_sqls = []
if re.search(r"where", parts[1], flags=re.IGNORECASE):
data = re.split(r"(?i) where", parts[1]) # 拆分" where"【无论大小写】
tail = " where" + data[1] # WHERE a = b ORDER BY misc
# message_p = "涉及到的数据源有:"
# print(message_p)
# time.sleep(sleep_time)
#
# message_p = data[0]
# print(message_p) # data1, data2, data3
# time.sleep(sleep_time)
divide_providers = data[0].split(", ")
# total = len(divide_providers)
# message_p = "拆分结果如下:"
# print(message_p)
for i in range(len(divide_providers)):
divide_sqls.append(head + divide_providers[i] + tail)
# message_p = str(i + 1) + ":" + divide_sqls[i]
# print(message_p)
else:
data = parts[1] # data1,data2,data3
divide_providers = data.split(",")
for i in range(len(divide_providers)):
divide_sqls.append(head + divide_providers[i])
# message_p = str(i + 1) + ":" + divide_sqls[i]
# print(message_p)
return divide_sqls
class SelectDatabase: # 定义类
def __init__(self, database):
self.database = database # 赋值数据库名称
def ret_hospital(self): # 定义函数返回字典——医院HOS这个表
# 连接服务器Server的数据库:
db = pymysql.connect(
host="localhost",
user="root",
password="111111",
db=f"{self.database}",
charset="utf8",
)
# 使用操作游标:
cursor = db.cursor()
sql = """SELECT * FROM HOS"""
cursor.execute(sql)
results = cursor.fetchall() # 获取查询结果的所有数据
hospital_dict = {} # 创建一个空字典
# 遍历查询结果,将每条消息数据存储到字典中:
for row in results:
hos_id = row[0] # 医院编号(HOS_ID)
hos_name = row[1] # 医院名称(HOS_NAME)
hos_add = row[2] # 医院地址(HOS_ADD)
hos_tel = row[3] # 医院电话(HOS_TEL)
# hospital_dict["医院编号"] = hos_id
# hospital_dict["医院名称"] = hos_name
# hospital_dict["医院地址"] = hos_add
# hospital_dict["医院电话"] = hos_tel
# # 打印字典内容
# print(hospital_dict)
""" 注释的输出形式:
{'医院编号': '001', '医院名称': '极光医院', '医院地址': '千里市广大区极光街道1-1', '医院电话': '023-6296666'}
{'医院编号': '002', '医院名称': '风舱医院', '医院地址': '风火市舱山区飞光街道1-1', '医院电话': '023-6286666'}
"""
# 将每个属性的值存储在对应的列表中
hospital_dict.setdefault("医院编号", []).append(hos_id)
hospital_dict.setdefault("医院名称", []).append(hos_name)
hospital_dict.setdefault("医院地址", []).append(hos_add)
hospital_dict.setdefault("医院电话", []).append(hos_tel)
db.close()
""" 当前返回的字典形式:
{'医院编号': ['001', '002'],
'医院名称': ['极光医院', '风舱医院'],
'医院地址': ['千里市广大区极光街道1-1',
'风火市舱山区飞光街道1-1'],
'医院电话': ['023-6296666', '023-6286666']}
"""
# 返回字典
return hospital_dict
def ret_doctor(self): # 定义函数返回字典——医生DOC这个表
# 连接服务器Server的数据库:
db = pymysql.connect(
host="localhost",
user="root",
password="111111",
db=f"{self.database}",
charset="utf8",
)
# 使用操作游标:
cursor = db.cursor()
sql = """SELECT * FROM DOC"""
cursor.execute(sql)
results = cursor.fetchall() # 获取查询结果的所有数据
doctor_dict = {} # 创建一个空字典
# 遍历查询结果,将每条消息数据存储到字典中:
for row in results:
doc_id = row[0] # 医生编号(DOC_ID)
doc_name = row[1] # 医生名称(DOC_NAME)
doc_tel = row[2] # 医生电话(DOC_TEL)
doc_qua = row[3] # 医院资质(DOC_QUA)
# hospital_dict["医生编号"] = doc_id
# hospital_dict["医生名称"] = doc_name
# hospital_dict["医院地址"] = doc_tel
# hospital_dict["医院电话"] = doc_qua
# # 打印字典内容
# print(doctor_dict)
# 将每个属性的值存储在对应的列表中
doctor_dict.setdefault("医院编号", []).append(doc_id)
doctor_dict.setdefault("医院名称", []).append(doc_name)
doctor_dict.setdefault("医院地址", []).append(doc_tel)
doctor_dict.setdefault("医院电话", []).append(doc_qua)
db.close()
""" 当前返回的字典形式:
{'医院编号': ['001', '002', '003'],
'医院名称': ['神医华佗', '扁鹊', '还医生'],
'医院地址': ['19666666666', '13666666666', '13546981623'],
'医院电话': ['主任医师', '主任医师', '医师']}
"""
# 返回字典
return doctor_dict
def ret_patient(self): # 定义函数返回字典——病人PAT这个表
# 连接服务器Server的数据库:
db = pymysql.connect(
host="localhost",
user="root",
password="111111",
db=f"{self.database}",
charset="utf8",
)
# 使用操作游标:
cursor = db.cursor()
sql = """SELECT * FROM PAT"""
cursor.execute(sql)
results = cursor.fetchall() # 获取查询结果的所有数据
patient_dict = {} # 创建一个空字典
# 遍历查询结果,将每条消息数据存储到字典中:
for row in results:
pat_id = row[0] # 病人编号(PAT_ID)
pat_name = row[1] # 病人姓名(PAT_NAME)
pat_tel = row[2] # 病人电话(PAT_TEL)
# patient_dict["病人编号"] = pat_id
# patient_dict["病人姓名"] = pat_name
# patient_dict["病人电话"] = pat_tel
# # 打印字典内容
# print(patient_dict)
# 将每个属性的值存储在对应的列表中
patient_dict.setdefault("病人编号", []).append(pat_id)
patient_dict.setdefault("病人姓名", []).append(pat_name)
patient_dict.setdefault("病人电话", []).append(pat_tel)
db.close()
""" 当前返回的字典形式:
{'病人编号': ['001', '002', '003', '004'],
'病人姓名': ['曹操', '蔡桓公', '去还', '刘备'],
'病人电话': ['66666666666', '02666666666', '01234567891', '98765432101']}
"""
# 返回字典
return patient_dict
def ret_diagnosis(self): # 定义函数返回字典——诊断DIA这个表
# 连接服务器Server的数据库:
db = pymysql.connect(
host="localhost",
user="root",
password="111111",
db=f"{self.database}",
charset="utf8",
)
# 使用操作游标:
cursor = db.cursor()
sql = """SELECT * FROM DIA"""
cursor.execute(sql)
results = cursor.fetchall() # 获取查询结果的所有数据
diagnosis_dict = {} # 创建一个空字典
# 遍历查询结果,将每条消息数据存储到字典中:
for row in results:
dia_id = row[0] # 诊号(DIA_ID)
doc_id = row[1] # 医生编号(DOC_ID)
pat_id = row[2] # 病人编号(PAT_ID)
time = row[3] # 时间(TIME)
cases = row[4] # 病例(CASES)
symptom = row[5] # 症状(SYMPTOM)
# diagnosis_dict["诊号"] = dia_id
# diagnosis_dict["医生编号"] = doc_id
# diagnosis_dict["病人编号"] = pat_id
# diagnosis_dict["时间"] = time
# diagnosis_dict["病例"] = cases
# diagnosis_dict["症状"] = symptom
# # 打印字典内容
# print(diagnosis_dict)
# 将每个属性的值存储在对应的列表中
diagnosis_dict.setdefault("诊号", []).append(dia_id)
diagnosis_dict.setdefault("医生编号", []).append(doc_id)
diagnosis_dict.setdefault("病人编号", []).append(pat_id)
diagnosis_dict.setdefault("时间", []).append(time)
diagnosis_dict.setdefault("病例", []).append(cases)
diagnosis_dict.setdefault("症状", []).append(symptom)
db.close()
""" 当前返回的字典形式:
{'诊号': ['001', '002', '003', '004', '005'],
'医生编号': ['001', '001', '002', '003', '003'],
'病人编号': ['001', '001', '002', '003', '004'],
'时间': ['2015.03.04', '2015.05.16', '2016.12.30', '2017.01.15', '2017.01.15'],
'病例': ['小感冒', '慢性头痛', '通风', '中风', '脚部内伤'], '症状': ['突然头痛', '头非常痛,不能睡觉', '怕凉', '伤口大量出血,且发烧', '崴脚,走路痛']}
"""
# 返回字典
return diagnosis_dict
def ret_define(self, sql): # 定义函数,返回自定义信息的字典
# 连接服务器Server的数据库:
db = pymysql.connect(
host="localhost",
user="root",
password="111111",
db=f"{self.database}",
charset="utf8",
)
try:
# 使用操作游标:
cursor = db.cursor()
cursor.execute(sql)
results = cursor.fetchall() # 获取查询结果的所有数据
# tables = extract_tables(sql) # 分离出sql语句中的表名
# 遍历查询结果,将每条消息都输出出来:
for row in results:
for i in range(len(row)):
print(f"{row[i]}\t", end="")
print()
except:
print("查询权限不足!或查询语句出错!")
def main(hospital_name):
sql = """SELECT *
FROM HOS, DOC, PAT, DIA
WHERE DOC.DOC_ID = DIA.DOC_ID AND
PAT.PAT_ID = DIA.PAT_ID
"""
hospital_name = hospital_name.replace("\n", "")
if hospital_name == "xx大学附属医院":
database = SelectDatabase("Hospital1")
database.ret_define(sql)
elif hospital_name == "xx阳光社区附属医院":
database = SelectDatabase("Hospital2")
database.ret_define(sql)
else:
print("暂无记录!")

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# algo_present
算法分析课程的展示

BIN
background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

471
data_provider.py Normal file
View File

@ -0,0 +1,471 @@
import socket
import sys
import threading
import time
import pickle
from io import StringIO
import CoreAlgorithm
import DataSearch
# 审批回执类消息head01001001
# sql密文类消息head01001010
# 元数据类消息head01001100
# 实现GUI界面
import tkinter as tk
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import ImageTk
# 美化
from ttkbootstrap import Style # pylint: disable=e0401 # type: ignore
from tkinter import ttk
sleep_time = 1
# 用于生成本地公钥和私钥
def generate_key_pair_data():
public_key_data, private_key_data = CoreAlgorithm.generate_paillier_keypair()
return private_key_data, public_key_data
# 用公钥为本地生成数字证书
def get_certificate(temp_public_key, cert_name):
public_key_str = "\n".join(
temp_public_key[i : i + 60] for i in range(0, len(temp_public_key), 60)
)
pack_public_key = (
"-----BEGIN PUBLIC KEY-----\n" + public_key_str + "\n-----END PUBLIC KEY-----"
)
cert = {"public_key": pack_public_key, "name": "<数据提供方>" + cert_name}
return cert
# 公钥转公钥信息
def key_to_data(key):
# str转bytes
byte = bytes.fromhex(key)
# bytes转PaillierPublicKey
data = pickle.loads(byte)
return data
# 加密字符串
def str_to_encrypt(message, public_data):
# str 转 int
if message.isdigit():
int_message = int(message)
else:
int_message = int.from_bytes(message.encode(), "big")
enc_message = public_data.encrypt(int_message)
print("int_message", int_message)
return enc_message
class MyClient:
def __init__(self):
# 实现GUI主界面框用到的参数
self.root = None
self.data_text = None
self.name_text = None
self.message_text = None
self.window = None
# 初始化最近一次的待处理的sql申请信息
self.recent_message = ""
# 初始化本端名
self.name = ""
# 初始化sql
self.sql = ""
# 准备界面函数
self.root_window()
self.give_name()
# 生成私钥和公钥信息
(
self.private_key_data,
self.public_key_data,
) = generate_key_pair_data() # PaillierPublicKey 类型
# 生成私钥和公钥字符串
self.private_key, self.public_key = self.generate_key_pair()
# 初始化数字证书
self.certificate = {} # 等名字输入了再生成
# 初始化socket
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 初始化根界面
def root_window(self):
self.root = tk.Tk()
self.root.title("数据提供方智慧医疗SQL查询系统")
self.root.geometry("450x540")
# 增加背景图片
global photo
photo = ImageTk.PhotoImage(file="background.png")
label = Label(self.root, image=photo)
label.pack()
self.create_widgets() # 调用函数创建功能按钮
# 为本端取名
def give_name(self):
self.window = tk.Toplevel()
self.window.title("命名窗口")
self.window.geometry("300x320")
# 初始化信息输入框
self.name_text = tk.StringVar()
tk.Label(self.window, bg="green", text="请为本端取名:").place(x=50, y=100)
input_message = tk.Entry(self.window, textvariable=self.name_text)
input_message.pack()
input_message.place(x=80, y=150)
# 确认按钮及位置
bt_confirm = tk.Button(
self.window, bg="green", text="确认", width=10, command=self.get_name
)
bt_confirm.pack()
bt_confirm.place(x=125, y=220)
# 读取输入框的name保存在self.name中
def get_name(self):
self.name = self.name_text.get()
messagebox.showinfo("提示", "命名成功!")
self.window.destroy()
self.root.title("<数据提供方>" + self.name + "的智慧医疗系统")
# 安全通信
def safe_connect(self):
if self.certificate != {}:
# 与服务器端地址建立通信, 8080为服务端程序的端口号
self.client.connect(("localhost", 1111))
# 为接收消息函数添加线程
threading.Thread(target=self.get_message).start()
time.sleep(3)
else:
messagebox.showinfo("提示", "请先生成你的公钥证书!")
# 向平台发送本地公钥信息
def send_public_key(self):
print("正在向平台发送本地公钥信息...")
self.client.send(str(self.certificate).encode())
print(self.certificate)
time.sleep(sleep_time)
print("发送成功!")
# 产生公私钥字符串
def generate_key_pair(self):
# Paillier 转 bytes
public_key_bytes = pickle.dumps(self.public_key_data)
private_key_bytes = pickle.dumps(self.private_key_data)
# bytes 转 str
public_key = public_key_bytes.hex()
private_key = private_key_bytes.hex()
return private_key, public_key
# 打印公钥
def print_public_key(self):
print("本地公钥信息为:")
print(self.public_key_data)
print("打印公钥如下:", end="")
public_key_str = "\n".join(
self.public_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_public_key = (
"\n-----BEGIN PUBLIC KEY-----\n"
+ public_key_str
+ "\n-----END PUBLIC KEY-----\n"
)
print(pack_public_key)
messagebox.showinfo("本地公钥", pack_public_key) # GUI界面显示
# 打印私钥
def print_private_key(self):
print("本地私钥信息为:")
print(self.private_key_data)
private_key_str = "\n".join(
self.private_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_private_key = (
"-----BEGIN PRIVATE KEY-----\n"
+ private_key_str
+ "\n-----END PRIVATE KEY-----\n"
)
print("打印私钥如下:", end="")
print(pack_private_key)
messagebox.showinfo("本地私钥", pack_private_key) # GUI界面显示
# 打印证书
def print_certificate(self):
if self.name != "":
self.certificate = get_certificate(self.public_key, self.name)
print("本地公钥证书为:")
message = ""
for key, value in self.certificate.items():
print(key, ":\n", value)
message += key + ":\n" + value + "\n"
messagebox.showinfo("本地公钥证书", message)
else:
messagebox.showinfo("提示", "请先为平台命名!")
# 接收消息
def get_message(self):
while True:
# 接收连接结果信息
message = self.client.recv(4096).decode()
print(message)
if message == "安全多方计算平台:单向授权成功!":
self.client.send("请发送平台的完整公钥证书".encode())
while True:
message = self.client.recv(4096).decode() # 公钥字符串比较长,要多一点
if message.startswith("{'public_key':"): # 等待接收平台公钥证书
cert = eval(message)
messagebox.showinfo("连接结果", "与平台连接成功!")
print("接收到的平台的公钥证书如下:")
message = ""
for key, value in cert.items():
if isinstance(value, bytes):
value = value.decode()
print(key, ":\n", value)
message += key + ":\n" + value
messagebox.showinfo("平台的公钥证书", message)
server_public_key = (
cert["public_key"]
.split("-----END PUBLIC KEY-----")[0]
.split("-----BEGIN PUBLIC KEY-----")[1]
)
server_public_key = server_public_key.replace("\n", "")
print("提取到的server_public_key:")
print(server_public_key)
global server_public_key_data
server_public_key_data = key_to_data(server_public_key)
print("对应的server_public_key_data:")
print(server_public_key_data)
messagebox.showinfo("平台的公钥信息", server_public_key_data)
self.client.send("认证成功!".encode())
self.send_public_key() # 单向认证后把自己的公钥证书发给平台实现双向认证
break
else:
print("错误的Message", message)
elif message == "安全多方计算平台:双向授权成功!":
messagebox.showinfo("平台发来的消息", "与平台的双向认证成功!")
self.client.send("请求查询方信息!".encode())
cert = self.client.recv(4096).decode()
cert = eval(cert)
message_p = "接收到一则非平台的公钥证书"
print(message_p)
# messagebox.showinfo("提示", message_p)
message = ""
for key, value in cert.items():
if isinstance(value, bytes):
value = value.decode()
print(key, ":\n", value)
message += key + ":\n" + value + "\n"
# messagebox.showinfo("数据查询方的公钥证书", message)
search_public_key = (
cert["public_key"]
.split("-----END PUBLIC KEY-----")[0]
.split("-----BEGIN PUBLIC KEY-----")[1]
)
search_public_key = search_public_key.replace("\n", "")
print("提取到的search_public_key:")
print(search_public_key)
global search_public_key_data
search_public_key_data = key_to_data(search_public_key)
print("对应的search_public_key_data:")
print(search_public_key_data)
# messagebox.showinfo("数据查询方的公钥信息", search_public_key_data)
elif message.startswith("01001010"):
message = message.split("01001010", 1)[
1
] # [0]是空字符串,已测试。只切一次是防止密文出现和头部一样的信息被误切。
# 使用私钥解密消息,获得sql明文
print("接收到的sql密文:", message)
int_message = int(message)
# Ciphertext转EncryptedNumber
Encrpt_message = CoreAlgorithm.EncryptedNumber(
self.public_key_data, int_message, exponent=0
)
dec_int_message = self.private_key_data.decrypt(Encrpt_message)
dec_message = dec_int_message.to_bytes(
(dec_int_message.bit_length() + 7) // 8, "big"
).decode()
print("解密后的消息为:", dec_message)
self.sql = dec_message.split("||")[2]
print("收到已授权方的sql:", self.sql)
self.design_window()
# --------------------------接收sql消息的窗口设计函数-------------------------
# 接受调用数据的请求
def send_accept_reply(self):
self.client.send(
(
"01001001"
+ str(self.client.getsockname())
+ "||"
+ self.name
+ "同意了你的数据申请。"
).encode()
)
self.window.destroy()
self.window = tk.Toplevel()
self.window.title("命名窗口")
self.window.geometry("300x320")
# 信息输入框
self.data_text = tk.StringVar()
tk.Label(self.window, bg="green", text="请输入要调用的信息:").place(x=50, y=100)
input_message = tk.Entry(self.window, textvariable=self.data_text)
input_message.pack()
input_message.place(x=80, y=150)
# 确认按钮及位置
bt_confirm = tk.Button(
self.window, bg="green", text="确认", width=10, command=self.send_data
)
bt_confirm.pack()
bt_confirm.place(x=125, y=220)
# 发送要调用的信息
def send_data(self):
message = self.data_text.get()
print(message, type(message))
# 加密并封装消息
print("正在封装并加密消息...")
global search_public_key_data
enc_message = str_to_encrypt(message, search_public_key_data).ciphertext()
pack_message = "01001100" + str(enc_message)
print("正在发送消息给平台...")
self.client.send(pack_message.encode())
print("发送成功!")
messagebox.showinfo("提示", "发送成功!")
self.window.destroy()
# 拒绝调用数据的请求
def send_decline_reply(self):
self.client.send(
(
"01001001" + str(self.client.getsockname()) + "||" + "想得美哦!不给(*^▽^*)"
).encode()
)
messagebox.showinfo("提示", "已拒绝!")
self.window.destroy()
# 稍后处理调用数据的请求
def wait_reply(self):
self.window.destroy()
# 接收到sql信息的专属窗口
def design_window(self):
if self.sql != "":
self.window = tk.Toplevel()
self.window.title("平台发来的消息")
self.window.geometry("550x320") # 设定窗口大小
self.recent_message = "收到已授权方的sql:" + self.sql
tk.Label(self.window, bg="green", text=self.recent_message).place(
x=50, y=100
)
# 创建接受按钮
accept_button = tk.Button(
self.window, text="接受", width=15, command=self.send_accept_reply
)
accept_button.place(x=90, y=220)
# 创建拒绝按钮
decline_button = tk.Button(
self.window, text="拒绝", width=15, command=self.send_decline_reply
)
decline_button.place(x=225, y=220)
# 创建稍后处理按钮
decline_button = tk.Button(
self.window, text="稍后处理", width=15, command=self.wait_reply
)
decline_button.place(x=360, y=220)
else:
messagebox.showinfo("提示", "暂无待处理的信息。")
# -----------------------------------------------------------------------
# 调用本地信息库
def search_data(self):
output = StringIO() # 用于保存打印信息
sys.stdout = output # 重定向sys.stdout到StringIO
print(self.name)
DataSearch.main(self.name)
sys.stdout = sys.__stdout__
long_text = output.getvalue()
print(long_text)
# 创建显示窗口
window = tk.Toplevel()
# 创建滚动文本部件
roll = scrolledtext.ScrolledText(window, width=200, height=40)
# 打印超长字符串
roll.insert(tk.END, long_text)
roll.pack()
# --------------------------主界面的按键功能绑定--------------------------------
# 界面按键
def create_widgets(self):
# 创建按钮和标签等部件并使用ttk和Style进行美化
style = Style(theme="darkly") # 指定样式主题
self.root = style.master
button1 = ttk.Button(
self.root,
text="查看我的公钥",
bootstyle="info-outline",
command=self.print_public_key,
width=30,
)
button1.place(x=104, y=310)
button2 = ttk.Button(
self.root,
text="查看我的私钥",
bootstyle="info-outline",
command=self.print_private_key,
width=30,
)
button2.place(x=104, y=348)
button3 = ttk.Button(
self.root,
text="生成我的证书",
bootstyle="info-outline",
command=self.print_certificate,
width=30,
)
button3.place(x=104, y=383)
button4 = ttk.Button(
self.root,
text="获取平台认证",
bootstyle="info-outline",
command=self.safe_connect,
width=30,
)
button4.place(x=104, y=418)
button5 = ttk.Button(
self.root,
text="处理请求信息",
bootstyle="info-outline",
command=self.design_window,
width=30,
)
button5.place(x=104, y=453)
button6 = ttk.Button(
self.root,
text="查看医疗记录",
bootstyle="info-outline",
command=self.search_data,
width=30,
)
button6.place(x=104, y=488)
# GUI界面
def run(self):
self.root.mainloop()
# ----------------------------------------------------主程序----------------------------------------------------
global server_public_key_data, search_public_key_data, photo # 使用全局变量,否则图片可能会被回收,不显示
# GUI界面
app = MyClient()
app.run()

508
data_requirer.py Normal file
View File

@ -0,0 +1,508 @@
import socket
import sys
import threading
import time
import pickle
from io import StringIO
import CoreAlgorithm
import DataSearch
# 审批回执类消息head01001001
# sql密文类消息head01001010
# 元数据类消息head01001100
# 实现GUI界面
import tkinter as tk
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import ImageTk
# 美化
from ttkbootstrap import Style # pylint: disable=e0401 # type: ignore
from tkinter import ttk
# 用于生成本地公钥和私钥
def generate_key_pair_data():
public_key_data, private_key_data = CoreAlgorithm.generate_paillier_keypair()
return private_key_data, public_key_data
# 用公钥为本地生成数字证书
def get_certificate(temp_public_key, cert_name):
public_key_str = "\n".join(
temp_public_key[i : i + 60] for i in range(0, len(temp_public_key), 60)
)
pack_public_key = (
"-----BEGIN PUBLIC KEY-----\n" + public_key_str + "\n-----END PUBLIC KEY-----"
)
cert = {"public_key": pack_public_key, "name": "<数据查询方>" + cert_name}
return cert
# 公钥转公钥信息
def key_to_data(key):
# str转bytes
byte = bytes.fromhex(key)
# bytes转PaillierPublicKey
data = pickle.loads(byte)
return data
# 加密字符串
def str_to_encrypt(message, public_data):
# str 转 int
if message.isdigit():
int_message = int(message)
else:
int_message = int.from_bytes(message.encode(), "big")
enc_message = public_data.encrypt(int_message)
print("int_message", int_message)
return enc_message
class MyClient:
def __init__(self):
# 实现GUI主界面框用到的参数
self.root = None
self.data_text = None
self.name_text = None
self.recent_message = None
self.window = None
self.sql_text = None
# 初始化本端名
self.name = ""
# 初始化sql
self.sql = ""
# 准备界面函数
self.root_window()
self.give_name()
# 生成私钥和公钥信息
(
self.private_key_data,
self.public_key_data,
) = generate_key_pair_data() # PaillierPublicKey 类型
# 生成私钥和公钥字符串
self.private_key, self.public_key = self.generate_key_pair()
# 获取数字证书
self.certificate = {} # 等名字输入了再生成
# 初始化socket
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 初始化根界面
def root_window(self):
self.root = tk.Tk()
self.root.title("数据查询方智慧医疗SQL查询系统")
self.root.geometry("450x660")
# 增加背景图片
global photo
photo = ImageTk.PhotoImage(file="background.png")
label = Label(self.root, image=photo)
label.pack()
self.create_widgets() # 调用函数创建功能按钮
# 为本端取名
def give_name(self):
self.window = tk.Toplevel()
self.window.title("命名窗口")
self.window.geometry("300x320")
# 初始化信息输入框
self.name_text = tk.StringVar()
tk.Label(self.window, bg="green", text="请为本端取名:").place(x=50, y=100)
input_message = tk.Entry(self.window, textvariable=self.name_text)
input_message.pack()
input_message.place(x=80, y=150)
# 确认按钮及位置
bt_confirm = tk.Button(
self.window, bg="green", text="确认", width=10, command=self.get_name
)
bt_confirm.pack()
bt_confirm.place(x=125, y=220)
# 读取输入框的name保存在self.name中
def get_name(self):
self.name = self.name_text.get()
messagebox.showinfo("提示", "命名成功!")
self.window.destroy()
self.root.title("<数据查询方>" + self.name + "的智慧医疗系统")
# 编写sql
def create_sql(self):
self.window = tk.Toplevel() # 建立窗口
self.window.title("编写sql语句") # 为窗口命名
self.window.geometry("580x270") # 设定窗口大小
# 初始化信息输入框
self.sql_text = tk.StringVar()
tk.Label(self.window, bg="green", text="请输入您需要的sql查询:").place(x=70, y=50)
input_message = tk.Entry(self.window, textvariable=self.sql_text, width=60)
input_message.place(x=70, y=100)
# 初始化确认按钮
bt_confirm = tk.Button(
self.window, bg="green", text="确认", width=60, command=self.get_sql
)
bt_confirm.place(x=70, y=150)
# self.sql = input("请编写你的sql:")
# 读取输入框的sql语句保存在self.sql中
def get_sql(self):
self.sql = self.sql_text.get()
if self.sql != "":
messagebox.showinfo("提示", "编写成功!")
else:
messagebox.showinfo("提示", "编写失败!语句不能为空!")
self.window.destroy()
# 安全通信
def safe_connect(self):
if self.certificate != {}:
# 与服务器端地址建立通信, 8080为服务端程序的端口号
self.client.connect(("localhost", 1111))
# 为接收消息函数添加线程
threading.Thread(target=self.get_message).start()
time.sleep(3)
else:
messagebox.showinfo("提示", "请先生成你的公钥证书!")
# 向平台发送本地公钥信息
def send_public_key(self):
print("正在向平台发送本地公钥信息...")
self.client.send(str(self.certificate).encode())
time.sleep(1)
print("发送成功!")
# 发送sql
def send_sql(self):
if self.sql != "":
print("正在封装并加密消息...")
message = self.deal_sql(self.sql)
print("处理后的message:", message)
print("正在发送消息给平台...")
self.client.send(message.encode())
print("发送成功!")
messagebox.showinfo("提示", "发送成功!") # GUI界面显示
else:
messagebox.showinfo("提示", "请先进行编写sql的操作确认您的需求") # GUI界面显示
# 加密封装sql语句
def deal_sql(self, context):
message = str(self.client.getsockname()) + "||" + context
global server_public_key_data
enc_message = str_to_encrypt(message, server_public_key_data) # 用平台的公钥进行加密
return "01001010" + str(enc_message.ciphertext()) # int 型
# 产生公私钥字符串
def generate_key_pair(self):
# Paillier 转 bytes
public_key_bytes = pickle.dumps(self.public_key_data)
private_key_bytes = pickle.dumps(self.private_key_data)
# bytes 转 str
public_key = public_key_bytes.hex()
private_key = private_key_bytes.hex()
return private_key, public_key
# 打印公钥
def print_public_key(self):
print("本地公钥信息为:")
print(self.public_key_data)
print("打印公钥如下:")
public_key_str = "\n".join(
self.public_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_public_key = (
"\n-----BEGIN PUBLIC KEY-----\n"
+ public_key_str
+ "\n-----END PUBLIC KEY-----\n"
)
print(pack_public_key)
# show_list()
messagebox.showinfo("本地公钥", pack_public_key) # GUI界面显示
# 打印私钥
def print_private_key(self):
print("本地私钥信息为:")
print(self.private_key_data)
private_key_str = "\n".join(
self.private_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_private_key = (
"-----BEGIN PRIVATE KEY-----\n"
+ private_key_str
+ "\n-----END PRIVATE KEY-----\n"
)
print("打印私钥如下:")
print(pack_private_key)
messagebox.showinfo("本地私钥", pack_private_key) # GUI界面显示
# 打印证书
def print_certificate(self):
if self.name != "":
self.certificate = get_certificate(self.public_key, self.name)
print("本地公钥证书为:")
message = ""
for key, value in self.certificate.items():
print(key, ":\n", value)
message += key + ":\n" + value + "\n"
messagebox.showinfo("本地公钥证书", message)
else:
messagebox.showinfo("提示", "请先为平台命名!")
# 接收消息
def get_message(self):
while True:
# 接收连接结果信息
message = self.client.recv(4096).decode()
print(message)
if message == "安全多方计算平台:单向授权成功!":
self.client.send("请发送平台的完整公钥证书".encode())
while True:
message = self.client.recv(4096).decode()
if message.startswith("{'public_key':"):
cert = eval(message)
messagebox.showinfo("连接结果", "与平台连接成功!")
print("接收到的平台的公钥证书如下:")
message = ""
for key, value in cert.items():
if isinstance(value, bytes):
value = value.decode()
print(key, ":\n", value)
message += key + ":\n" + value
messagebox.showinfo("平台的公钥证书", message)
server_public_key = (
cert["public_key"]
.split("-----END PUBLIC KEY-----")[0]
.split("-----BEGIN PUBLIC KEY-----")[1]
)
server_public_key = server_public_key.replace("\n", "")
print("提取到的server_public_key:")
print(server_public_key)
global server_public_key_data
server_public_key_data = key_to_data(server_public_key)
print("对应的server_public_key_data:")
print(server_public_key_data)
messagebox.showinfo("平台的公钥信息", server_public_key_data)
self.client.send("认证成功!".encode())
self.send_public_key() # 单向认证后把自己的公钥证书发给平台实现双向认证
break
else:
print("错误的Message", message)
elif message == "安全多方计算平台:双向授权成功!":
messagebox.showinfo("平台发来的消息", "与平台的双向认证成功!")
elif message.startswith("01001010"):
message = message.split("01001010", 1)[
1
] # [0]是空字符串,已测试。只切一次是防止密文出现和头部一样的信息被误切。
# 使用私钥解密消息,获得sql明文
print("接收到的sql密文:", message)
int_message = int(message)
# Ciphertext转EncryptedNumber
Encrpt_message = CoreAlgorithm.EncryptedNumber(
self.public_key_data, int_message, exponent=0
)
dec_int_message = self.private_key_data.decrypt(Encrpt_message)
dec_message = dec_int_message.to_bytes(
(dec_int_message.bit_length() + 7) // 8, "big"
).decode()
print("解密后的消息为:", dec_message)
self.sql = dec_message.split("||")[2]
print("收到已授权方的sql:", self.sql)
self.design_window()
elif message.startswith("结果:"):
message = message.split("结果:")[1]
if message != "正在等待接收其他信息...":
int_message = int(message)
# Ciphertext转EncryptedNumber
Encrpt_message = CoreAlgorithm.EncryptedNumber(
self.public_key_data, int_message, exponent=0
)
dec_int_message = self.private_key_data.decrypt(Encrpt_message)
print("分析结果:", dec_int_message)
messagebox.showinfo("分析结果", dec_int_message)
else:
messagebox.showinfo("提示", message)
# --------------------------接收sql消息的窗口设计函数-------------------------
# 接受调用数据的请求
def send_accept_reply(self):
self.client.send(
(
"01001001" + str(self.client.getsockname()) + "||安全多方平台同意了你的数据申请。"
).encode()
)
self.window = tk.Toplevel()
self.window.title("命名窗口")
self.window.geometry("300x320")
# 信息输入框
self.data_text = tk.StringVar()
tk.Label(self.window, bg="green", text="请输入要调用的信息:").place(x=50, y=100)
input_message = tk.Entry(self.window, textvariable=self.data_text)
input_message.pack()
input_message.place(x=80, y=150)
# 确认按钮及位置
bt_confirm = tk.Button(
self.window, bg="green", text="确认", width=10, command=self.send_data
)
bt_confirm.pack()
bt_confirm.place(x=125, y=220)
# 发送要调用的信息
def send_data(self):
message = self.name_text.get()
# 加密并封装消息
print("正在封装并加密消息...")
enc_message = str_to_encrypt(message, self.public_key_data).ciphertext()
pack_message = "01001100" + str(enc_message)
print("正在发送消息给平台...")
self.client.send(pack_message.encode())
print("发送成功!")
messagebox.showinfo("提示", "发送成功!")
self.window.destroy()
# 拒绝调用数据的请求
def send_decline_reply(self):
self.client.send(
(
"01001001" + str(self.client.getsockname()) + "||" + "想得美哦!不给(*^▽^*)"
).encode()
)
messagebox.showinfo("提示", "已拒绝!")
self.window.destroy()
# 稍后处理调用数据的请求
def wait_reply(self):
self.window.destroy()
# 接收到sql信息的专属窗口
def design_window(self):
if self.sql != "":
self.window = tk.Toplevel()
self.window.title("平台发来的消息")
self.window.geometry("550x320") # 设定窗口大小
self.recent_message = "收到已授权方的sql:" + self.sql
tk.Label(self.window, bg="green", text=self.recent_message).place(
x=50, y=100
)
# 创建接受按钮
accept_button = tk.Button(
self.window, text="接受", width=15, command=self.send_accept_reply
)
accept_button.place(x=90, y=220)
# 创建拒绝按钮
decline_button = tk.Button(
self.window, text="拒绝", width=15, command=self.send_decline_reply
)
decline_button.place(x=225, y=220)
# 创建稍后处理按钮
decline_button = tk.Button(
self.window, text="稍后处理", width=15, command=self.wait_reply
)
decline_button.place(x=360, y=220)
else:
messagebox.showinfo("提示", "暂无待处理的信息。")
# --------------------------------------------------------------------------
# 调用本地信息库
def search_data(self):
output = StringIO() # 用于保存打印信息
sys.stdout = output # 重定向sys.stdout到StringIO
print(self.name)
DataSearch.main(self.name)
sys.stdout = sys.__stdout__
long_text = output.getvalue()
print(long_text)
# 创建显示窗口
window = tk.Toplevel()
# 创建滚动文本部件
roll = scrolledtext.ScrolledText(window, width=200, height=40)
# 打印超长字符串
roll.insert(tk.END, long_text)
roll.pack()
# --------------------------主界面的按键功能绑定--------------------------------
# 界面按键
def create_widgets(self):
# 创建按钮和标签等部件并使用ttk和Style进行美化
style = Style(theme="darkly") # 指定样式主题
self.root = style.master
button1 = ttk.Button(
self.root,
text="查看我的公钥",
bootstyle="info-outline",
command=self.print_public_key,
width=30,
)
button1.place(x=104, y=360)
button2 = ttk.Button(
self.root,
text="查看我的私钥",
bootstyle="info-outline",
command=self.print_private_key,
width=30,
)
button2.place(x=104, y=398)
button3 = ttk.Button(
self.root,
text="生成我的证书",
bootstyle="info-outline",
command=self.print_certificate,
width=30,
)
button3.place(x=104, y=433)
button4 = ttk.Button(
self.root,
text="获取平台认证",
bootstyle="info-outline",
command=self.safe_connect,
width=30,
)
button4.place(x=104, y=468)
button5 = ttk.Button(
self.root,
text="调用SQL查询",
bootstyle="info-outline",
command=self.create_sql,
width=30,
)
button5.place(x=104, y=503)
button6 = ttk.Button(
self.root,
text="发送SQL请求",
bootstyle="info-outline",
command=self.send_sql,
width=30,
)
button6.place(x=104, y=538)
button7 = ttk.Button(
self.root,
text="处理请求信息",
bootstyle="info-outline",
command=self.design_window,
width=30,
)
button7.place(x=104, y=573)
button8 = ttk.Button(
self.root,
text="查看医疗记录",
bootstyle="info-outline",
command=self.search_data,
width=30,
)
button8.place(x=104, y=608)
# GUI界面
def run(self):
self.root.mainloop()
# ----------------------------------------------------主程序----------------------------------------------------
global server_public_key_data, photo # 使用全局变量,否则图片可能会被回收,不显示
# GUI界面
app = MyClient()
app.run()

162
encoding.py Normal file
View File

@ -0,0 +1,162 @@
import math
import sys
class EncodedNumber(object):
BASE = 16
"""Base to use when exponentiating. Larger `BASE` means
that :attr:`exponent` leaks less information. If you vary this,
you'll have to manually inform anyone decoding your numbers.
"""
LOG2_BASE = math.log(BASE, 2)
FLOAT_MANTISSA_BITS = sys.float_info.mant_dig
def __init__(self, public_key, encoding, exponent):
self.public_key = public_key
self.encoding = encoding
self.exponent = exponent
@classmethod
def encode(cls, public_key, scalar, precision=None, max_exponent=None):
"""Return an encoding of an int or float.
This encoding is carefully chosen so that it supports the same
operations as the Paillier cryptosystem.
If *scalar* is a float, first approximate it as an int, `int_rep`:
scalar = int_rep * (:attr:`BASE` ** :attr:`exponent`),
for some (typically negative) integer exponent, which can be
tuned using *precision* and *max_exponent*. Specifically,
:attr:`exponent` is chosen to be equal to or less than
*max_exponent*, and such that the number *precision* is not
rounded to zero.
Having found an integer representation for the float (or having
been given an int `scalar`), we then represent this integer as
a non-negative integer < :attr:`~PaillierPublicKey.temp_n`.
Paillier homomorphic arithemetic works modulo
:attr:`~PaillierPublicKey.temp_n`. We take the convention that a
number x < temp_n/3 is positive, and that a number x > 2n/3 is
negative. The range temp_n/3 < x < 2n/3 allows for overflow
detection.
Args:
public_key (PaillierPublicKey): public key for which to encode
(this is necessary because :attr:`~PaillierPublicKey.temp_n`
varies).
scalar: an int or float to be encrypted.
If int, it must satisfy abs(*value*) <
:attr:`~PaillierPublicKey.temp_n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
:attr:`~PaillierPublicKey.temp_n`/3
(i.e. if a float is near the limit then detectable
overflow may still occur)
precision (float): Choose exponent (i.e. fix the precision) so
that this number is distinguishable from zero. If `scalar`
is a float, then this is set so that minimal precision is
lost. Lower precision leads to smaller encodings, which
might yield faster computation.
max_exponent (int): Ensure that the exponent of the returned
`EncryptedNumber` is at most this.
Returns:
EncodedNumber: Encoded form of *scalar*, ready for encryption
against *publickey*.
"""
# Calculate the maximum exponent for desired precision
if precision is None:
if isinstance(scalar, int):
prec_exponent = 0
elif isinstance(scalar, float):
# Encode with *at least* as much precision as the python float
# What's the base-2 exponent on the float?
bin_flt_exponent = math.frexp(scalar)[1]
# What's the base-2 exponent of the least significant bit?
# The least significant bit has value 2 ** bin_lsb_exponent
bin_lsb_exponent = bin_flt_exponent - cls.FLOAT_MANTISSA_BITS
# What's the corresponding base BASE exponent? Round that down.
prec_exponent = math.floor(bin_lsb_exponent / cls.LOG2_BASE)
else:
raise TypeError("Don't know the precision of type %s."
% type(scalar))
else:
prec_exponent = math.floor(math.log(precision, cls.BASE))
# Remember exponents are negative for numbers < 1.
# If we're going to store numbers with a more negative
# exponent than demanded by the precision, then we may
# as well bump up the actual precision.
if max_exponent is None:
exponent = prec_exponent
else:
exponent = min(max_exponent, prec_exponent)
int_rep = int(round(scalar * pow(cls.BASE, -exponent)))
if abs(int_rep) > public_key.max_int:
raise ValueError('Integer needs to be within +/- %d but got %d'
% (public_key.max_int, int_rep))
# Wrap negative numbers by adding temp_n
return cls(public_key, int_rep % public_key.n, exponent)
def decode(self):
"""Decode plaintext and return the result.
Returns:
an int or float: the decoded number. N.B. if the number
returned is an integer, it will not be of type float.
Raises:
OverflowError: if overflow is detected in the decrypted number.
"""
if self.encoding >= self.public_key.n:
# Should be mod temp_n
raise ValueError('Attempted to decode corrupted number')
elif self.encoding <= self.public_key.max_int:
# Positive
mantissa = self.encoding
elif self.encoding >= self.public_key.n - self.public_key.max_int:
# Negative
mantissa = self.encoding - self.public_key.n
else:
raise OverflowError('Overflow detected in decrypted number')
return mantissa * pow(self.BASE, self.exponent)
def decrease_exponent_to(self, new_exp):
"""Return an `EncodedNumber` with same value but lower exponent.
If we multiply the encoded value by :attr:`BASE` and decrement
:attr:`exponent`, then the decoded value does not change. Thus
we can almost arbitrarily ratchet down the exponent of an
:class:`EncodedNumber` - we only run into trouble when the encoded
integer overflows. There may not be a warning if this happens.
This is necessary when adding :class:`EncodedNumber` instances,
and can also be useful to hide information about the precision
of numbers - e.g. a protocol can fix the exponent of all
transmitted :class:`EncodedNumber` to some lower bound(s).
Args:
new_exp (int): the desired exponent.
Returns:
EncodedNumber: Instance with the same value and desired
exponent.
Raises:
ValueError: You tried to increase the exponent, which can't be
done without decryption.
"""
if new_exp > self.exponent:
raise ValueError('New exponent %i should be more negative than'
'old exponent %i' % (new_exp, self.exponent))
factor = pow(self.BASE, self.exponent - new_exp)
new_enc = self.encoding * factor % self.public_key.n
return self.__class__(self.public_key, new_enc, new_exp)

10
note.txt Normal file
View File

@ -0,0 +1,10 @@
编写的sql格式硬性规定
含有from多个对象需要用,分割
要先定好测试案例sql语句然后才方便用if/else跑结果
中央人民医院
xx阳光社区诊所
xx大学附属医院
select count(*) from xx阳光社区诊所, xx大学附属医院 where diag = "cancer";

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
pymysql
wxPython

562
server.py Normal file
View File

@ -0,0 +1,562 @@
import socket
import time
import pickle
import wx # pylint: disable=e0401 # type: ignore
import CoreAlgorithm
import threading
import DataSearch
import server_demo
sleep_time = 0.2
# 审批回执类消息head01001001
# sql密文类消息head01001010
# 元数据类消息head01001100
# 用于生成本地公钥和私钥信息
def generate_key_pair_data():
public_key_data, private_key_data = CoreAlgorithm.generate_paillier_keypair()
return private_key_data, public_key_data
# 从公钥证书中提取公钥信息
def get_public_key_data(message):
message = eval(message.replace("\n", ""))
public_key = (
message["public_key"]
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
) # 分割得到公钥
public_key_bytes = bytes.fromhex(public_key)
public_key_data = pickle.loads(public_key_bytes)
return public_key_data
# 用公钥为本地生成数字证书
def get_certificate(temp_public_key, cert_name):
public_key_str = "\n".join(
temp_public_key[i : i + 60] for i in range(0, len(temp_public_key), 60)
)
pack_public_key = (
"-----BEGIN PUBLIC KEY-----\n" + public_key_str + "\n-----END PUBLIC KEY-----\n"
)
cert = {"public_key": pack_public_key, "name": cert_name}
return cert
# 加密字符串
def str_to_encrypt(message, public_data):
# str 转 int
if message.isdigit():
int_message = int(message)
else:
int_message = int.from_bytes(message.encode(), "big")
enc_message = public_data.encrypt(int_message)
print("int_message", int_message)
return enc_message
class MyServer(server_demo.MyFrame):
def __init__(self, parent):
server_demo.MyFrame.__init__(self, parent)
# 生成私钥和公钥信息
self.private_key_data, self.public_key_data = generate_key_pair_data()
# 生成私钥和公钥字符串
self.private_key, self.public_key = self.generate_key_pair()
# 获取数字证书
self.certificate = get_certificate(self.public_key, "安全多方服务器")
# 初始化当前sql
self.sql = ""
# 初始化sql拆分对象
self.divide_sqls = []
# 初始化sql拆分数据源
self.divide_providers = []
# 记录属于同一个请求的元数据密文
self.datas = []
# 初始化数据查询方的公钥证书为str在发来过后为其赋值
self.search_cert = ""
# 初始化socket
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口
self.server.bind(("localhost", 1111))
# 设置最大监听数
self.server.listen(5)
# 设置一个字典,用来保存每一个客户端的连接和身份信息
self.socket_mapping = {} # temp_socket: [addr, 公钥信息]
# 设置接收的最大字节数
self.maxSize = 4096
# 记录调用方地址
self.source = None
# 记录收集信息的数量
self.flag = 0
# 记录需要收集的信息总量
self.total = 0
# 保存安全多方计算结果
self.result = 0
self.out_look()
# 等待客户端连接
message_p = "等待客户端连接..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# 添加消息记录列
def out_look(self):
self.m_listCtrl1.InsertColumn(0, "消息记录") # 为聊天框添加‘消息记录’列
self.m_listCtrl1.SetColumnWidth(0, 1000)
self.m_listCtrl2.InsertColumn(0, "消息记录") # 为聊天框添加‘消息记录’列
self.m_listCtrl2.SetColumnWidth(0, 1000)
self.m_listCtrl3.InsertColumn(0, "消息记录") # 为聊天框添加‘消息记录’列
self.m_listCtrl3.SetColumnWidth(0, 1000)
# 建立连接,设置线程
def run(self):
while True:
client_socket, addr = self.server.accept()
# 发送信息,提示客户端已成功连接
message_p = "{0}连接成功!".format(addr)
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# 将客户端socket等信息存入字典
self.socket_mapping[client_socket] = []
self.socket_mapping[client_socket].append(addr)
message_p = "安全多方计算平台:单向授权成功!"
client_socket.send(message_p.encode())
self.m_listCtrl2.Append([message_p])
time.sleep(sleep_time)
# 创建线程,负责接收客户端信息并转发给其他客户端
threading.Thread(
target=self.recv_from_client, args=(client_socket,)
).start()
# 产生公私钥字符串
def generate_key_pair(self):
# Paillier 转 bytes
public_key_bytes = pickle.dumps(self.public_key_data)
private_key_bytes = pickle.dumps(self.private_key_data)
# bytes 转 str
public_key = public_key_bytes.hex()
private_key = private_key_bytes.hex()
return private_key, public_key
# 接收客户端消息并转发
def recv_from_client(self, client_socket): # client_socket指的是连接到的端口socket
while True:
message = client_socket.recv(self.maxSize).decode("utf-8")
message_p = "接收到来自{0}的message:\n{1}".format(
self.socket_mapping[client_socket][0], message
)
print(message_p)
self.m_listCtrl1.Append([message_p]) # 准备文件传输
if message.startswith("01001001"):
message_p = "正在解析消息内容..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# 去掉审批回执的头部
message = message.split("01001001", 1)[
1
] # [0]是空字符串,已测试。只切一次是防止密文出现和头部一样的信息被误切。
# 认证发送者的合法性
sender = message.split("||")[0]
context = message.split("||")[1]
message_p = "接收到来自{0}的message:\n{1}".format(sender, context)
print(message_p)
self.m_listCtrl1.Append([message_p])
# time.sleep(sleep_time)
self.flag += 1
if context == "想得美哦!不给(*^▽^*)":
self.flag = -9999
elif message.startswith("01001010"):
message_p = "正在解析消息内容..."
print(message_p)
self.m_listCtrl3.Append([message_p])
# time.sleep(sleep_time)
# 认证发送者的合法性
if len(self.socket_mapping[client_socket]) > 1: # 如果发送者的公钥信息已被收集
# 识别明文中一起发送的发送目标 明文应是发送者||发送内容(||时间戳等),对象用socket表示吧...
message = message.split("01001010", 1)[
1
] # [0]是空字符串,已测试。只切一次是防止密文出现和头部一样的信息被误切。
# 用发送目标之前给的公钥加密明文,得到密文。
# 去掉sql密文的头部
# 使用平台私钥解密消息,获得sql明文
message_p = "接收到的sql密文:" + message
print(message_p)
self.m_listCtrl1.Append([message_p])
time.sleep(sleep_time)
int_message = int(message)
# Ciphertext转EncryptedNumber
Encrpt_message = CoreAlgorithm.EncryptedNumber(
self.public_key_data, int_message, exponent=0
)
dec_int_message = self.private_key_data.decrypt(Encrpt_message)
dec_message = dec_int_message.to_bytes(
(dec_int_message.bit_length() + 7) // 8, "big"
).decode()
message_p = "解密后的消息为:" + dec_message
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
self.source = dec_message.split("||")[0]
self.sql = dec_message.split("||")[1]
message_p = "收到已授权方的sql:" + self.sql
print(message_p)
self.m_listCtrl1.Append([message_p])
time.sleep(sleep_time)
message_p = "待处理的sql语句为:" + self.sql
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
message_p = "正在拆分sql..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
self.divide_providers = DataSearch.extract_tables(self.sql)
message_p = "涉及到的数据持有对象有:" + str(self.divide_providers)
print(message_p)
self.m_listCtrl3.Append(([message_p]))
self.divide_sqls = DataSearch.divide_sql(self.sql)
message_p = "正在分别加密和封装sql..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
self.pack_sqls()
message_p = "发送成功!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
else:
message_p = "非授权对象,禁止访问!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# show_list()
elif message.startswith("01001100"):
message_p = "正在解析消息内容..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# 去掉元数据头部
message = message.split("01001100", 1)[
1
] # [0]是空字符串,已测试。只切一次是防止密文出现和头部一样的信息被误切。
# 把元数据存入本地数据库的临时表里格式provider + encode_data
# print("message:", message)
int_message = int(message)
message_p = "收到元数据为:{}".format(int_message)
print(message_p)
self.m_listCtrl1.Append([message_p])
# 根据证书找公钥信息
search_public_key = (
self.search_cert["public_key"]
.split("-----END PUBLIC KEY-----")[0]
.split("-----BEGIN PUBLIC KEY-----")[1]
)
search_public_key = search_public_key.replace("\n", "")
print("提取到的search_public_key:")
print(search_public_key)
# str转bytes
byte = bytes.fromhex(search_public_key)
# bytes转PaillierPublicKey
search_public_key_data = pickle.loads(byte)
print("对应的search_public_key_data:")
print(search_public_key_data)
# int密 -- EncryptedNumber密
Encrpt_message = CoreAlgorithm.EncryptedNumber(
search_public_key_data, int_message, exponent=0
)
self.datas.append(Encrpt_message)
# Ciphertext转EncryptedNumber
# print("int_message:", int_message)
# Encrpt_message = CoreAlgorithm.EncryptedNumber(self.public_key_data, int_message, exponent=0)
# print("Enc:", Encrpt_message)
# dec_int_message = self.private_key_data.decrypt(Encrpt_message)
# print("dec:", dec_int_message)
# dec_message = dec_int_message.to_bytes((dec_int_message.bit_length() + 7) // 8, 'big').decode()
# print("解密后的消息为:", dec_message) # 已测试,说明平台不可解密元数据
self.safe_calculate()
elif message == "请发送平台的完整公钥证书":
message_p = "正在发送证书..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
message_p = str(self.certificate)
client_socket.send(message_p.encode()) # 二进制传输
self.m_listCtrl2.Append([message_p])
time.sleep(sleep_time)
message_p = "发送完成!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
elif message.startswith("{'public_key':"):
print(message)
print(self.socket_mapping)
print(get_public_key_data(message))
self.socket_mapping[client_socket].append(
get_public_key_data(message)
) # 绑定端口与公钥信息的关系
print(self.socket_mapping)
cert = eval(message)
print(cert, type(cert)) # 字典型
if cert["name"].startswith("<数据查询方>"):
self.search_cert = cert # 字典型
self.socket_mapping[client_socket].append(cert["name"]) # 绑定端口与用户身份的关系
message_p = "接收到一则公钥证书:"
print(message_p)
self.m_listCtrl1.Append([message_p])
time.sleep(sleep_time)
message_p = ""
for key, value in cert.items():
if isinstance(value, bytes):
value = value.decode()
print(key, ":", value)
message_p = key + ":\n" + value
print(message_p)
self.m_listCtrl1.Append([message_p])
time.sleep(sleep_time)
message_p = "发送完成!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
message_p = "安全多方计算平台:双向授权成功!"
print(message_p)
self.m_listCtrl2.Append([message_p])
client_socket.send(message_p.encode("utf-8")) # 二进制传输
time.sleep(sleep_time)
message_p = "使用对象表已更新:"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
print(self.socket_mapping)
self.m_listCtrl3.Append([self.socket_mapping])
elif message == "请求查询方信息!":
if str(self.search_cert) != "":
message_p = "正在发送提供方的证书..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
message_p = str(self.search_cert)
client_socket.send(message_p.encode()) # 二进制传输
self.m_listCtrl2.Append([message_p])
time.sleep(sleep_time)
else:
client_socket.send(" ".encode()) # 二进制传输
for key, value in self.socket_mapping.items():
message_p = str(key) + ":" + str(value) + "\n"
print(message_p)
self.m_listCtrl3.Append([message_p])
elif message == "":
pass
elif message == "认证成功!":
pass
else:
message_p = "Message:" + message
print(message_p)
self.m_listCtrl1.Append([message_p])
time.sleep(sleep_time)
message_p = "错误的消息格式,丢弃!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# 打印公钥
def print_public_key(self, event):
message_p = "本地公钥信息为:"
print(message_p)
self.m_listCtrl3.Append([message_p])
message_p = self.public_key_data
print(message_p)
self.m_listCtrl3.Append([message_p])
message_p = "打印公钥如下:"
print(message_p)
self.m_listCtrl3.Append([message_p])
public_key_str = "\n".join(
self.public_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_public_key = (
"-----BEGIN PUBLIC KEY-----\n"
+ public_key_str
+ "\n-----END PUBLIC KEY-----\n"
)
message_p = pack_public_key
print(message_p)
message = message_p.split("\n") # 设置打印格式,因为显示窗打印不了\n
for i in range(len(message)):
self.m_listCtrl3.Append([message[i]])
# show_list()
# 打印私钥
def print_private_key(self, event):
message_p = "本地私钥信息为:"
print(message_p)
self.m_listCtrl3.Append([message_p])
message_p = self.private_key_data
print(message_p)
self.m_listCtrl3.Append([message_p])
private_key_str = "\n".join(
self.private_key[i : i + 60] for i in range(0, len(self.public_key), 60)
)
pack_private_key = (
"-----BEGIN PRIVATE KEY-----\n"
+ private_key_str
+ "\n-----END PRIVATE KEY-----\n"
)
message_p = "打印私钥如下:"
print(message_p)
self.m_listCtrl3.Append([message_p])
message_p = pack_private_key
print(message_p)
message = message_p.split("\n") # 设置打印格式,因为显示窗打印不了\n
for i in range(len(message)):
self.m_listCtrl3.Append([message[i]])
# 打印证书
def print_certificate(self, event):
message_p = "本地公钥证书为:"
print(message_p)
self.m_listCtrl3.Append([message_p])
for key, value in self.certificate.items():
message_p = key + ":"
print(message_p)
self.m_listCtrl3.Append([message_p])
if key == "public_key":
value = value.split("\n")
for i in range(len(value)):
self.m_listCtrl3.Append([value[i]])
else:
self.m_listCtrl3.Append([value])
# show_list()
# 加密封装sqls并发送
def pack_sqls(self):
for key, value in self.socket_mapping.items():
for i in range(len(self.divide_providers)):
if (
self.divide_providers[i] in value[2]
): # eg: value[2] == "<数据提供方>风舱医院"
for j in range(len(self.divide_sqls)):
if (
self.divide_providers[i] in self.divide_sqls[j]
): # 如果发送目标和信息匹配)
sql = (
str(self.source)
+ "||"
+ str(key.getsockname())
+ "||"
+ self.divide_sqls[i]
)
print(sql)
int_enc_sql = str_to_encrypt(
sql, value[1]
).ciphertext() # 用接收者的公钥加密消息
message_p = "01001010" + str(int_enc_sql)
key.send(message_p.encode())
self.m_listCtrl2.Append([message_p])
message_p = "已将消息{0}发送给{1},其地址为{2}".format(
self.divide_sqls[j],
self.divide_providers[i],
key.getsockname(),
)
print(message_p)
self.m_listCtrl3.Append([message_p])
# 安全算法
def safe_calculate(self):
self.total = len(self.divide_providers)
if self.flag == self.total:
message_p = "正在进行安全多方计算分析..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# #################安全多方计算分析过程##############
if "select count(*) from xx阳光社区诊所, xx大学附属医院" in self.sql:
print(self.datas)
for x in self.datas:
self.result = self.result + x
# EncryptedNumber密 -- int密
self.result = self.result.ciphertext()
# int密 -- str密
self.result = str(self.result)
message = "分析成功!"
print(message)
self.m_listCtrl3.Append([message])
# EncryptedNumber 转 int
# self.result = self.result.ciphertext()
message = "结果:" + str(self.result)
print(message)
self.m_listCtrl3.Append([message])
time.sleep(sleep_time)
message_p = "正在发送结果给申请人..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
for key, value in self.socket_mapping.items():
if value[2].startswith("<数据查询方>"):
key.send(message.encode())
# 重置参数
self.total = 0
self.flag = 0
self.result = 0
self.datas = []
elif self.flag < 0:
message_p = "结果:已有数据持有方拒绝了提供消息的请求,安全分析无法进行,分析失败!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
for key, value in self.socket_mapping.items():
if value[2].startswith("<数据查询方>"):
key.send(message_p.encode())
# 重置参数
self.total = 0
self.flag = 0
else:
message_p = "结果:正在等待接收其他信息..."
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
for key, value in self.socket_mapping.items():
if value[2].startswith("<数据查询方>"):
key.send(message_p.encode())
message_p = "发送完成!"
print(message_p)
self.m_listCtrl3.Append([message_p])
time.sleep(sleep_time)
# ----------------------------------------------------主程序----------------------------------------------------
app = wx.App()
frame = MyServer(None)
frame.Show(True) # 展示登录页面
threading.Thread(target=frame.run).start() # 在新线程中运行服务器
app.MainLoop()

262
server_demo.py Normal file
View File

@ -0,0 +1,262 @@
import wx # pylint: disable=e0401 # type: ignore
import wx.xrc # pylint: disable=e0401 # type: ignore
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(
self,
parent,
id=wx.ID_ANY,
title="安全多方服务器平台",
pos=wx.DefaultPosition,
size=wx.Size(444, 749),
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
)
self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
self.SetFont(wx.Font(5, 70, 90, 90, False, "宋体"))
self.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
self.SetBackgroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
)
fgSizer1 = wx.FlexGridSizer(0, 2, 0, 0)
fgSizer1.SetFlexibleDirection(wx.BOTH)
fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
bSizer11 = wx.BoxSizer(wx.VERTICAL)
self.m_bitmap11 = wx.StaticBitmap(
self, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.Size(70, 30), 0
)
bSizer11.Add(self.m_bitmap11, 0, wx.ALL, 5)
self.m_staticline211 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline211.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
self.m_staticline211.SetMaxSize(wx.Size(80, -1))
bSizer11.Add(self.m_staticline211, 0, wx.EXPAND | wx.ALL, 5)
self.m_staticText1 = wx.StaticText(
self, wx.ID_ANY, "接收记录", wx.DefaultPosition, wx.Size(-1, 30), 0
)
self.m_staticText1.Wrap(-1)
self.m_staticText1.SetFont(wx.Font(11, 70, 90, 90, False, "宋体"))
self.m_staticText1.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer11.Add(self.m_staticText1, 0, wx.ALL, 5)
self.m_bitmap1 = wx.StaticBitmap(
self, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.Size(70, 111), 0
)
bSizer11.Add(self.m_bitmap1, 0, wx.ALL, 5)
self.m_staticline21 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline21.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
self.m_staticline21.SetMaxSize(wx.Size(80, -1))
bSizer11.Add(self.m_staticline21, 0, wx.EXPAND | wx.ALL, 5)
self.m_staticText11 = wx.StaticText(
self, wx.ID_ANY, "发送记录", wx.DefaultPosition, wx.Size(-1, 30), 0
)
self.m_staticText11.Wrap(-1)
self.m_staticText11.SetFont(wx.Font(11, 70, 90, 90, False, "宋体"))
self.m_staticText11.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer11.Add(self.m_staticText11, 0, wx.ALL, 5)
self.m_bitmap12 = wx.StaticBitmap(
self, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.Size(70, 111), 0
)
bSizer11.Add(self.m_bitmap12, 0, wx.ALL, 5)
self.m_staticline212 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline212.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
self.m_staticline212.SetMaxSize(wx.Size(80, -1))
bSizer11.Add(self.m_staticline212, 0, wx.EXPAND | wx.ALL, 5)
self.m_staticText111 = wx.StaticText(
self, wx.ID_ANY, "当前状态", wx.DefaultPosition, wx.Size(-1, 30), 0
)
self.m_staticText111.Wrap(-1)
self.m_staticText111.SetFont(wx.Font(11, 70, 90, 90, False, "宋体"))
self.m_staticText111.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer11.Add(self.m_staticText111, 0, wx.ALL, 5)
fgSizer1.Add(bSizer11, 1, wx.EXPAND, 5)
bSizer1 = wx.BoxSizer(wx.HORIZONTAL)
bSizer2 = wx.BoxSizer(wx.VERTICAL)
self.m_staticText = wx.StaticText(
self, wx.ID_ANY, "安全多方平台服务器", wx.DefaultPosition, wx.Size(-1, 30), 0
)
self.m_staticText.Wrap(-1)
self.m_staticText.SetFont(wx.Font(16, 70, 90, 92, False, "宋体"))
self.m_staticText.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer2.Add(self.m_staticText, 0, wx.ALL, 5)
self.m_staticline1 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(1, 2), wx.LI_HORIZONTAL
)
self.m_staticline1.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
bSizer2.Add(self.m_staticline1, 0, wx.EXPAND | wx.ALL, 5)
self.m_listCtrl1 = wx.ListCtrl(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(360, 150), wx.LC_REPORT
)
self.m_listCtrl1.SetFont(wx.Font(9, 70, 90, 90, False, "宋体"))
self.m_listCtrl1.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer2.Add(self.m_listCtrl1, 0, wx.ALL, 5)
self.m_staticline2 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline2.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
bSizer2.Add(self.m_staticline2, 0, wx.EXPAND | wx.ALL, 5)
self.m_listCtrl2 = wx.ListCtrl(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(360, 150), wx.LC_REPORT
)
self.m_listCtrl2.SetFont(wx.Font(9, 70, 90, 90, False, "宋体"))
self.m_listCtrl2.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer2.Add(self.m_listCtrl2, 0, wx.ALL, 5)
self.m_staticline22 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline22.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
bSizer2.Add(self.m_staticline22, 0, wx.EXPAND | wx.ALL, 5)
self.m_listCtrl3 = wx.ListCtrl(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(360, 150), wx.LC_REPORT
)
self.m_listCtrl3.SetFont(wx.Font(9, 70, 90, 90, False, "宋体"))
self.m_listCtrl3.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer2.Add(self.m_listCtrl3, 0, wx.ALL, 5)
self.m_staticline221 = wx.StaticLine(
self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, 2), wx.LI_HORIZONTAL
)
self.m_staticline221.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
)
bSizer2.Add(self.m_staticline221, 0, wx.EXPAND | wx.ALL, 5)
bSizer12 = wx.BoxSizer(wx.VERTICAL)
bSizer102 = wx.BoxSizer(wx.HORIZONTAL)
self.m_button31 = wx.Button(
self, wx.ID_ANY, "显示本地公钥", wx.DefaultPosition, wx.Size(300, 30), 0
)
self.m_button31.SetFont(wx.Font(11, 70, 90, 90, False, wx.EmptyString))
self.m_button31.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer102.Add(self.m_button31, 0, wx.ALIGN_CENTER | wx.ALL, 5)
bSizer12.Add(bSizer102, 1, wx.EXPAND, 5)
bSizer1012 = wx.BoxSizer(wx.HORIZONTAL)
self.m_button41 = wx.Button(
self, wx.ID_ANY, "显示本地私钥", wx.DefaultPosition, wx.Size(300, 30), 0
)
self.m_button41.SetFont(wx.Font(11, 70, 90, 90, False, wx.EmptyString))
self.m_button41.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer1012.Add(self.m_button41, 0, wx.ALIGN_CENTER | wx.ALL, 5)
bSizer12.Add(bSizer1012, 1, wx.EXPAND, 5)
bSizer10111 = wx.BoxSizer(wx.HORIZONTAL)
self.m_button51 = wx.Button(
self, wx.ID_ANY, "打印本地证书", wx.DefaultPosition, wx.Size(300, 30), 0
)
self.m_button51.SetFont(wx.Font(11, 70, 90, 90, False, wx.EmptyString))
self.m_button51.SetForegroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
)
bSizer10111.Add(self.m_button51, 0, wx.ALIGN_CENTER | wx.ALL, 5)
bSizer12.Add(bSizer10111, 1, wx.EXPAND, 5)
bSizer2.Add(bSizer12, 1, wx.EXPAND, 5)
bSizer1.Add(bSizer2, 1, wx.EXPAND, 5)
fgSizer1.Add(bSizer1, 1, wx.EXPAND, 5)
self.SetSizer(fgSizer1)
self.Layout()
self.Centre(wx.BOTH)
# Connect Events
self.m_button31.Bind(wx.EVT_BUTTON, self.print_public_key)
self.m_button41.Bind(wx.EVT_BUTTON, self.print_private_key)
self.m_button51.Bind(wx.EVT_BUTTON, self.print_certificate)
def __del__(self):
pass
# Virtual event handlers, override them in your derived class
def print_public_key(self, event):
event.Skip()
def print_private_key(self, event):
event.Skip()
def print_certificate(self, event):
event.Skip()

2286
util.py Normal file

File diff suppressed because it is too large Load Diff