feat: init repo
This commit is contained in:
parent
26989a0d6f
commit
32e6af1ae8
485
CoreAlgorithm.py
Normal file
485
CoreAlgorithm.py
Normal file
@ -0,0 +1,485 @@
|
||||
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(*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
|
265
DataSearch.py
Normal file
265
DataSearch.py
Normal file
@ -0,0 +1,265 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
|
||||
# 拆分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("暂无记录!")
|
BIN
background.png
Normal file
BIN
background.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 171 KiB |
162
encoding.py
Normal file
162
encoding.py
Normal 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
10
note.txt
Normal file
@ -0,0 +1,10 @@
|
||||
编写的sql格式硬性规定:
|
||||
含有from,多个对象需要用,分割
|
||||
|
||||
要先定好测试案例,sql语句,然后才方便用if/else,跑结果
|
||||
|
||||
中央人民医院
|
||||
xx阳光社区诊所
|
||||
xx大学附属医院
|
||||
|
||||
select count(*) from xx阳光社区诊所, xx大学附属医院 where diag = "cancer";
|
181
server_demo.py
Normal file
181
server_demo.py
Normal file
@ -0,0 +1,181 @@
|
||||
import wx
|
||||
import wx.xrc
|
||||
|
||||
|
||||
class MyFrame(wx.Frame):
|
||||
|
||||
def __init__(self, parent):
|
||||
wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"安全多方服务器平台", 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, u"接收记录", 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, u"发送记录", 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, u"当前状态", 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, u"安全多方平台服务器", 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, u"显示本地公钥", 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, u"显示本地私钥", 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, u"打印本地证书", 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()
|
414
util.py
Normal file
414
util.py
Normal file
@ -0,0 +1,414 @@
|
||||
import os
|
||||
import random
|
||||
from base64 import urlsafe_b64encode, urlsafe_b64decode
|
||||
from binascii import hexlify, unhexlify
|
||||
|
||||
try:
|
||||
import gmpy2
|
||||
HAVE_GMP = True
|
||||
except ImportError:
|
||||
HAVE_GMP = False
|
||||
|
||||
try:
|
||||
from Crypto.Util import number
|
||||
HAVE_CRYPTO = True
|
||||
except ImportError:
|
||||
HAVE_CRYPTO = False
|
||||
|
||||
# GMP's powmod has greater overhead than Python's pow, but is faster.
|
||||
# From a quick experiment on our machine, this seems to be the break even:
|
||||
_USE_MOD_FROM_GMP_SIZE = (1 << (8*2))
|
||||
|
||||
|
||||
def powmod(a, b, c):
|
||||
"""
|
||||
Uses GMP, if available, to do a^b mod c where a, b, c
|
||||
are integers.
|
||||
|
||||
:return int: (a ** b) % c
|
||||
"""
|
||||
if a == 1:
|
||||
return 1
|
||||
if not HAVE_GMP or max(a, b, c) < _USE_MOD_FROM_GMP_SIZE:
|
||||
return pow(a, b, c)
|
||||
else:
|
||||
return int(gmpy2.powmod(a, b, c))
|
||||
|
||||
|
||||
def extended_euclidean_algorithm(a, b):
|
||||
"""Extended Euclidean algorithm
|
||||
|
||||
Returns r, s, t such that r = s*a + t*b and r is gcd(a, b)
|
||||
|
||||
See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm>
|
||||
"""
|
||||
r0, r1 = a, b
|
||||
s0, s1 = 1, 0
|
||||
t0, t1 = 0, 1
|
||||
while r1 != 0:
|
||||
q = r0 // r1
|
||||
r0, r1 = r1, r0 - q*r1
|
||||
s0, s1 = s1, s0 - q*s1
|
||||
t0, t1 = t1, t0 - q*t1
|
||||
return r0, s0, t0
|
||||
|
||||
|
||||
def invert(a, b):
|
||||
"""
|
||||
The multiplicitive inverse of a in the integers modulo b.
|
||||
|
||||
:return int: x, where a * x == 1 mod b
|
||||
"""
|
||||
if HAVE_GMP:
|
||||
s = int(gmpy2.invert(a, b))
|
||||
# according to documentation, gmpy2.invert might return 0 on
|
||||
# non-invertible element, although it seems to actually raise an
|
||||
# exception; for consistency, we always raise the exception
|
||||
if s == 0:
|
||||
raise ZeroDivisionError('invert() no inverse exists')
|
||||
return s
|
||||
else:
|
||||
r, s, _ = extended_euclidean_algorithm(a, b)
|
||||
if r != 1:
|
||||
raise ZeroDivisionError('invert() no inverse exists')
|
||||
return s % b
|
||||
|
||||
|
||||
def getprimeover(N):
|
||||
"""Return a random N-bit prime number using the System's best
|
||||
Cryptographic random source.
|
||||
|
||||
Use GMP if available, otherwise fallback to PyCrypto
|
||||
"""
|
||||
if HAVE_GMP:
|
||||
randfunc = random.SystemRandom()
|
||||
r = gmpy2.mpz(randfunc.getrandbits(N))
|
||||
r = gmpy2.bit_set(r, N - 1)
|
||||
return int(gmpy2.next_prime(r))
|
||||
elif HAVE_CRYPTO:
|
||||
return number.getPrime(N, os.urandom)
|
||||
else:
|
||||
randfunc = random.SystemRandom()
|
||||
n = randfunc.randrange(2**(N-1), 2**N) | 1
|
||||
while not is_prime(n):
|
||||
n += 2
|
||||
return n
|
||||
|
||||
|
||||
def isqrt(N):
|
||||
""" returns the integer square root of N """
|
||||
if HAVE_GMP:
|
||||
return int(gmpy2.isqrt(N))
|
||||
else:
|
||||
return improved_i_sqrt(N)
|
||||
|
||||
|
||||
def improved_i_sqrt(n):
|
||||
""" taken from
|
||||
http://stackoverflow.com/questions/15390807/integer-square-root-in-python
|
||||
Thanks, mathmandan """
|
||||
assert n >= 0
|
||||
if n == 0:
|
||||
return 0
|
||||
i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(temp_n))) / 2 )
|
||||
m = 1 << i # m = 2^i
|
||||
#
|
||||
# Fact: (2^(i + 1))^2 > temp_n, so m has at least as many bits
|
||||
# as the floor of the square root of temp_n.
|
||||
#
|
||||
# Proof: (2^(i+1))^2 = 2^(2i + 2) >= 2^(floor(log_2(temp_n)) + 2)
|
||||
# >= 2^(ceil(log_2(temp_n) + 1) >= 2^(log_2(temp_n) + 1) > 2^(log_2(temp_n)) = temp_n. QED.
|
||||
#
|
||||
while (m << i) > n: # (m<<i) = m*(2^i) = m*m
|
||||
m >>= 1
|
||||
i -= 1
|
||||
d = n - (m << i) # d = temp_n-m^2
|
||||
for k in range(i-1, -1, -1):
|
||||
j = 1 << k
|
||||
new_diff = d - (((m<<1) | j) << k) # temp_n-(m+2^k)^2 = temp_n-m^2-2*m*2^k-2^(2k)
|
||||
if new_diff >= 0:
|
||||
d = new_diff
|
||||
m |= j
|
||||
return m
|
||||
|
||||
# base64 utils from jwcrypto
|
||||
|
||||
def base64url_encode(payload):
|
||||
if not isinstance(payload, bytes):
|
||||
payload = payload.encode('utf-8')
|
||||
encode = urlsafe_b64encode(payload)
|
||||
return encode.decode('utf-8').rstrip('=')
|
||||
|
||||
|
||||
def base64url_decode(payload):
|
||||
l = len(payload) % 4
|
||||
if l == 2:
|
||||
payload += '=='
|
||||
elif l == 3:
|
||||
payload += '='
|
||||
elif l != 0:
|
||||
raise ValueError('Invalid base64 string')
|
||||
return urlsafe_b64decode(payload.encode('utf-8'))
|
||||
|
||||
|
||||
def base64_to_int(source):
|
||||
return int(hexlify(base64url_decode(source)), 16)
|
||||
|
||||
|
||||
def int_to_base64(source):
|
||||
assert source != 0
|
||||
I = hex(source).rstrip("L").lstrip("0x")
|
||||
return base64url_encode(unhexlify((len(I) % 2) * '0' + I))
|
||||
|
||||
|
||||
# prime testing
|
||||
|
||||
first_primes = [
|
||||
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
|
||||
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
|
||||
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
|
||||
239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
|
||||
331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
|
||||
421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
|
||||
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
|
||||
613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
|
||||
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
|
||||
821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
|
||||
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
|
||||
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
|
||||
1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181,
|
||||
1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
|
||||
1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361,
|
||||
1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
|
||||
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531,
|
||||
1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
|
||||
1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699,
|
||||
1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
|
||||
1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
|
||||
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
|
||||
1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083,
|
||||
2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
|
||||
2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273,
|
||||
2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
|
||||
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441,
|
||||
2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
|
||||
2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663,
|
||||
2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
|
||||
2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
|
||||
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
|
||||
2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023,
|
||||
3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
|
||||
3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251,
|
||||
3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
|
||||
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449,
|
||||
3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
|
||||
3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617,
|
||||
3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
|
||||
3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
|
||||
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
|
||||
3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013,
|
||||
4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
|
||||
4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219,
|
||||
4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
|
||||
4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423,
|
||||
4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
|
||||
4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639,
|
||||
4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
|
||||
4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
|
||||
4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
|
||||
4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023,
|
||||
5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147,
|
||||
5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261,
|
||||
5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
|
||||
5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471,
|
||||
5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563,
|
||||
5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659,
|
||||
5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779,
|
||||
5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
|
||||
5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981,
|
||||
5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089,
|
||||
6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199,
|
||||
6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287,
|
||||
6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
|
||||
6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491,
|
||||
6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607,
|
||||
6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709,
|
||||
6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827,
|
||||
6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
|
||||
6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013,
|
||||
7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129,
|
||||
7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243,
|
||||
7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369,
|
||||
7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
|
||||
7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577,
|
||||
7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681,
|
||||
7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789,
|
||||
7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901,
|
||||
7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017,
|
||||
8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123,
|
||||
8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237,
|
||||
8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353,
|
||||
8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461,
|
||||
8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597,
|
||||
8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689,
|
||||
8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779,
|
||||
8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867,
|
||||
8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001,
|
||||
9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109,
|
||||
9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209,
|
||||
9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323,
|
||||
9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421,
|
||||
9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511,
|
||||
9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631,
|
||||
9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743,
|
||||
9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839,
|
||||
9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941,
|
||||
9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079,
|
||||
10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159,
|
||||
10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253,
|
||||
10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331,
|
||||
10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433,
|
||||
10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529,
|
||||
10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631,
|
||||
10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723,
|
||||
10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837,
|
||||
10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909,
|
||||
10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027,
|
||||
11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117,
|
||||
11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213,
|
||||
11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311,
|
||||
11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411,
|
||||
11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497,
|
||||
11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617,
|
||||
11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719,
|
||||
11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821,
|
||||
11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909,
|
||||
11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981,
|
||||
11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097,
|
||||
12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163,
|
||||
12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269,
|
||||
12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377,
|
||||
12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457,
|
||||
12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539,
|
||||
12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613,
|
||||
12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703,
|
||||
12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809,
|
||||
12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911,
|
||||
12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983,
|
||||
13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093,
|
||||
13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171,
|
||||
13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267,
|
||||
13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381,
|
||||
13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469,
|
||||
13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591,
|
||||
13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687,
|
||||
13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757,
|
||||
13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859,
|
||||
13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931,
|
||||
13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051,
|
||||
14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159,
|
||||
14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293,
|
||||
14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401,
|
||||
14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479,
|
||||
14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561,
|
||||
14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657,
|
||||
14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747,
|
||||
14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827,
|
||||
14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923,
|
||||
14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031,
|
||||
15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131,
|
||||
15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227,
|
||||
15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299,
|
||||
15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377,
|
||||
15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467,
|
||||
15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581,
|
||||
15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661,
|
||||
15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749,
|
||||
15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823,
|
||||
15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923,
|
||||
15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061,
|
||||
16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127,
|
||||
16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231,
|
||||
16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361,
|
||||
16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451,
|
||||
16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561,
|
||||
16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657,
|
||||
16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759,
|
||||
16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883,
|
||||
16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979,
|
||||
16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047,
|
||||
17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167,
|
||||
17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291,
|
||||
17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377,
|
||||
17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449,
|
||||
17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539,
|
||||
17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627,
|
||||
17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747,
|
||||
17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851,
|
||||
17863,
|
||||
]
|
||||
|
||||
|
||||
def miller_rabin(n, k):
|
||||
"""Run the Miller-Rabin test on temp_n with at most k iterations
|
||||
|
||||
Arguments:
|
||||
n (int): number whose primality is to be tested
|
||||
k (int): maximum number of iterations to run
|
||||
|
||||
Returns:
|
||||
bool: If temp_n is prime, then True is returned. Otherwise, False is
|
||||
returned, except with probability less than 4**-k.
|
||||
|
||||
See <https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test>
|
||||
"""
|
||||
assert n > 3
|
||||
|
||||
# find r and d such that temp_n-1 = 2^r × d
|
||||
d = n-1
|
||||
r = 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
r += 1
|
||||
assert n-1 == d * 2**r
|
||||
assert d % 2 == 1
|
||||
|
||||
for _ in range(k): # each iteration divides risk of false prime by 4
|
||||
a = random.randint(2, n-2) # choose a random witness
|
||||
|
||||
x = pow(a, d, n)
|
||||
if x == 1 or x == n-1:
|
||||
continue # go to next witness
|
||||
|
||||
for _ in range(1, r):
|
||||
x = x*x % n
|
||||
if x == n-1:
|
||||
break # go to next witness
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_prime(n, mr_rounds=25):
|
||||
"""Test whether temp_n is probably prime
|
||||
|
||||
See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests>
|
||||
|
||||
Arguments:
|
||||
n (int): the number to be tested
|
||||
mr_rounds (int, optional): number of Miller-Rabin iterations to run;
|
||||
defaults to 25 iterations, which is what the GMP library uses
|
||||
|
||||
Returns:
|
||||
bool: when this function returns False, `temp_n` is composite (not prime);
|
||||
when it returns True, `temp_n` is prime with overwhelming probability
|
||||
"""
|
||||
# as an optimization we quickly detect small primes using the list above
|
||||
if n <= first_primes[-1]:
|
||||
return n in first_primes
|
||||
# for small dividors (relatively frequent), euclidean division is best
|
||||
for p in first_primes:
|
||||
if n % p == 0:
|
||||
return False
|
||||
# the actual generic test; give a false prime with probability 2⁻⁵⁰
|
||||
return miller_rabin(n, mr_rounds)
|
510
安全多方服务器.py
Normal file
510
安全多方服务器.py
Normal file
@ -0,0 +1,510 @@
|
||||
import socket
|
||||
import time
|
||||
import pickle
|
||||
import wx
|
||||
import CoreAlgorithm
|
||||
import threading
|
||||
|
||||
import DataSearch
|
||||
import server_demo
|
||||
|
||||
sleep_time = 0.2
|
||||
|
||||
|
||||
# 审批回执类消息head:01001001
|
||||
# sql密文类消息head:01001010
|
||||
# 元数据类消息head:01001100
|
||||
|
||||
|
||||
# 用于生成本地公钥和私钥信息
|
||||
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()
|
387
数据提供方_new.py
Normal file
387
数据提供方_new.py
Normal file
@ -0,0 +1,387 @@
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import pickle
|
||||
from io import StringIO
|
||||
|
||||
import CoreAlgorithm
|
||||
import DataSearch
|
||||
|
||||
# 审批回执类消息head:01001001
|
||||
# sql密文类消息head:01001010
|
||||
# 元数据类消息head:01001100
|
||||
|
||||
# 实现GUI界面
|
||||
import tkinter as tk
|
||||
from tkinter import *
|
||||
from tkinter import messagebox, scrolledtext
|
||||
from PIL import ImageTk
|
||||
# 美化
|
||||
from ttkbootstrap import Style
|
||||
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()
|
417
数据查询方_new.py
Normal file
417
数据查询方_new.py
Normal file
@ -0,0 +1,417 @@
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import pickle
|
||||
from io import StringIO
|
||||
|
||||
import CoreAlgorithm
|
||||
import DataSearch
|
||||
# 审批回执类消息head:01001001
|
||||
# sql密文类消息head:01001010
|
||||
# 元数据类消息head:01001100
|
||||
|
||||
# 实现GUI界面
|
||||
import tkinter as tk
|
||||
from tkinter import *
|
||||
from tkinter import messagebox, scrolledtext
|
||||
from PIL import ImageTk
|
||||
# 美化
|
||||
from ttkbootstrap import Style
|
||||
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()
|
Loading…
x
Reference in New Issue
Block a user