modify code style
This commit is contained in:
parent
b2354738fe
commit
4f62e02b88
@ -2,10 +2,12 @@ import random
|
|||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from encoding import EncodedNumber
|
from encoding import EncodedNumber
|
||||||
from util import invert, powmod, getprimeover
|
from util import invert, powmod, getprimeover
|
||||||
|
from visualize import show_name_args
|
||||||
|
|
||||||
DEFAULT_KEYSIZE = 1024 # 定义默认的二进制数长度
|
DEFAULT_KEYSIZE = 1024 # 定义默认的二进制数长度
|
||||||
|
|
||||||
|
|
||||||
|
@show_name_args
|
||||||
def generate_paillier_keypair(
|
def generate_paillier_keypair(
|
||||||
private_keyring=None, n_length=DEFAULT_KEYSIZE
|
private_keyring=None, n_length=DEFAULT_KEYSIZE
|
||||||
): # 生成公钥和私钥的函数
|
): # 生成公钥和私钥的函数
|
||||||
@ -33,6 +35,7 @@ def generate_paillier_keypair(
|
|||||||
return public_key, private_key # 返回公钥和私钥
|
return public_key, private_key # 返回公钥和私钥
|
||||||
|
|
||||||
|
|
||||||
|
@show_name_args
|
||||||
class PaillierPublicKey(object): # 定义公钥类
|
class PaillierPublicKey(object): # 定义公钥类
|
||||||
def __init__(self, n):
|
def __init__(self, n):
|
||||||
self.g = n + 1
|
self.g = n + 1
|
||||||
@ -42,7 +45,9 @@ class PaillierPublicKey(object): # 定义公钥类
|
|||||||
|
|
||||||
def __repr__(self): # 用于打印出该类的对象
|
def __repr__(self): # 用于打印出该类的对象
|
||||||
public_key_hash = hex(hash(self))[2:]
|
public_key_hash = hex(hash(self))[2:]
|
||||||
return "<PaillierPublicKey {}>".format(public_key_hash[:10]) # 返回表示对象的字符串
|
return "<PaillierPublicKey {}>".format(
|
||||||
|
public_key_hash[:10]
|
||||||
|
) # 返回表示对象的字符串
|
||||||
|
|
||||||
def __eq__(self, other): # 用于比较两个对象是否相等,并返回比较结果
|
def __eq__(self, other): # 用于比较两个对象是否相等,并返回比较结果
|
||||||
return self.n == other.n
|
return self.n == other.n
|
||||||
@ -53,11 +58,15 @@ class PaillierPublicKey(object): # 定义公钥类
|
|||||||
def get_n_and_g(self): # 获取该公钥的 n 和 g 的值
|
def get_n_and_g(self): # 获取该公钥的 n 和 g 的值
|
||||||
return self.n, self.g
|
return self.n, self.g
|
||||||
|
|
||||||
def raw_encrypt(self, plaintext, r_value=None): # 用于返回加密后的密文,其中r_value可给随机数赋值
|
def raw_encrypt(
|
||||||
|
self, plaintext, r_value=None
|
||||||
|
): # 用于返回加密后的密文,其中r_value可给随机数赋值
|
||||||
if not isinstance(plaintext, int): # 判断plaintext是否是整数
|
if not isinstance(plaintext, int): # 判断plaintext是否是整数
|
||||||
raise TypeError("明文不是整数,而是: %s" % type(plaintext))
|
raise TypeError("明文不是整数,而是: %s" % type(plaintext))
|
||||||
|
|
||||||
if self.n - self.max_int <= plaintext < self.n: # 对于非常大的明文,使用特殊的计算方法进行加密:
|
if (
|
||||||
|
self.n - self.max_int <= plaintext < self.n
|
||||||
|
): # 对于非常大的明文,使用特殊的计算方法进行加密:
|
||||||
neg_plaintext = self.n - plaintext # = abs(plaintext - nsquare)
|
neg_plaintext = self.n - plaintext # = abs(plaintext - nsquare)
|
||||||
neg_ciphertext = (self.n * neg_plaintext + 1) % self.nsquare
|
neg_ciphertext = (self.n * neg_plaintext + 1) % self.nsquare
|
||||||
nude_ciphertext = invert(neg_ciphertext, self.nsquare)
|
nude_ciphertext = invert(neg_ciphertext, self.nsquare)
|
||||||
@ -85,7 +94,9 @@ class PaillierPublicKey(object): # 定义公钥类
|
|||||||
encoding = EncodedNumber.encode(self, value, precision)
|
encoding = EncodedNumber.encode(self, value, precision)
|
||||||
return self.encrypt_encoded(encoding, r_value)
|
return self.encrypt_encoded(encoding, r_value)
|
||||||
|
|
||||||
def encrypt_encoded(self, encoding, r_value): # 将已编码的数值对象转换为加密后的数值对象,并可以选择进行混淆处理
|
def encrypt_encoded(
|
||||||
|
self, encoding, r_value
|
||||||
|
): # 将已编码的数值对象转换为加密后的数值对象,并可以选择进行混淆处理
|
||||||
obfuscator = r_value or 1 # 为随机数r_value,没有则默认为1
|
obfuscator = r_value or 1 # 为随机数r_value,没有则默认为1
|
||||||
ciphertext = self.raw_encrypt(encoding.encoding, r_value=obfuscator)
|
ciphertext = self.raw_encrypt(encoding.encoding, r_value=obfuscator)
|
||||||
encrypted_number = EncryptedNumber(self, ciphertext, encoding.exponent)
|
encrypted_number = EncryptedNumber(self, ciphertext, encoding.exponent)
|
||||||
@ -143,7 +154,9 @@ class PaillierPrivateKey(object): # 私钥
|
|||||||
"参数应该是EncryptedNumber," " 参数不能为: %s" % type(encrypted_number)
|
"参数应该是EncryptedNumber," " 参数不能为: %s" % type(encrypted_number)
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.public_key != encrypted_number.public_key: # 如果公钥与加密数字的公钥不一致
|
if (
|
||||||
|
self.public_key != encrypted_number.public_key
|
||||||
|
): # 如果公钥与加密数字的公钥不一致
|
||||||
raise ValueError("加密信息不能被不同的公钥进行加密!")
|
raise ValueError("加密信息不能被不同的公钥进行加密!")
|
||||||
|
|
||||||
if Encoding is None: # 将Encoding设置为未赋值的EncodedNumber变量
|
if Encoding is None: # 将Encoding设置为未赋值的EncodedNumber变量
|
||||||
@ -214,8 +227,12 @@ class PaillierPrivateKeyring(Mapping): # 私钥环类,并继承了Mapping类
|
|||||||
|
|
||||||
def add(self, private_key): # 向私钥环中添加私钥
|
def add(self, private_key): # 向私钥环中添加私钥
|
||||||
if not isinstance(private_key, PaillierPrivateKey): # 对要添加的私钥进行判断
|
if not isinstance(private_key, PaillierPrivateKey): # 对要添加的私钥进行判断
|
||||||
raise TypeError("私钥应该是PaillierPrivateKey类型, " "而不是 %s" % type(private_key))
|
raise TypeError(
|
||||||
self.__keyring[private_key.public_key] = private_key # 将该公钥和对用的私钥一块儿加入到私钥环中
|
"私钥应该是PaillierPrivateKey类型, " "而不是 %s" % type(private_key)
|
||||||
|
)
|
||||||
|
self.__keyring[private_key.public_key] = (
|
||||||
|
private_key # 将该公钥和对用的私钥一块儿加入到私钥环中
|
||||||
|
)
|
||||||
|
|
||||||
def decrypt(self, encrypted_number): # 对密文进行解密
|
def decrypt(self, encrypted_number): # 对密文进行解密
|
||||||
relevant_private_key = self.__keyring[
|
relevant_private_key = self.__keyring[
|
||||||
@ -242,7 +259,9 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
): # 如果公钥不是PaillierPublicKey
|
): # 如果公钥不是PaillierPublicKey
|
||||||
raise TypeError("公钥必须是PaillierPublicKey")
|
raise TypeError("公钥必须是PaillierPublicKey")
|
||||||
|
|
||||||
def __add__(self, other): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的加法
|
def __add__(
|
||||||
|
self, other
|
||||||
|
): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的加法
|
||||||
if isinstance(other, EncryptedNumber):
|
if isinstance(other, EncryptedNumber):
|
||||||
return self._add_encrypted(other)
|
return self._add_encrypted(other)
|
||||||
elif isinstance(other, EncodedNumber):
|
elif isinstance(other, EncodedNumber):
|
||||||
@ -256,7 +275,9 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
def __mul__(self, other): # 运算符重载,重载为EncryptedNumber与(整数/浮点数)的乘法
|
def __mul__(self, other): # 运算符重载,重载为EncryptedNumber与(整数/浮点数)的乘法
|
||||||
# 判断other对象是否是EncryptedNumber,如果是:
|
# 判断other对象是否是EncryptedNumber,如果是:
|
||||||
if isinstance(other, EncryptedNumber):
|
if isinstance(other, EncryptedNumber):
|
||||||
raise NotImplementedError("EncryptedNumber 与 EncryptedNumber 之间不能相乘!")
|
raise NotImplementedError(
|
||||||
|
"EncryptedNumber 与 EncryptedNumber 之间不能相乘!"
|
||||||
|
)
|
||||||
|
|
||||||
if isinstance(other, EncodedNumber):
|
if isinstance(other, EncodedNumber):
|
||||||
encoding = other
|
encoding = other
|
||||||
@ -269,7 +290,9 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
def __rmul__(self, other): # 反乘,处理整数/浮点数与EncryptedNumber之间的乘法
|
def __rmul__(self, other): # 反乘,处理整数/浮点数与EncryptedNumber之间的乘法
|
||||||
return self.__mul__(other)
|
return self.__mul__(other)
|
||||||
|
|
||||||
def __sub__(self, other): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的减法
|
def __sub__(
|
||||||
|
self, other
|
||||||
|
): # 运算符重载,重载为EncryptedNumber与(EncryptedNumber/整数/浮点数)的减法
|
||||||
return self + (other * -1)
|
return self + (other * -1)
|
||||||
|
|
||||||
def __rsub__(self, other): # 处理整数/浮点数与EncryptedNumber之间的减法
|
def __rsub__(self, other): # 处理整数/浮点数与EncryptedNumber之间的减法
|
||||||
@ -310,9 +333,13 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
self, new_exp
|
self, new_exp
|
||||||
): # 返回一个指数较低但大小相同的数(即返回一个同值的,但指数较低的EncryptedNumber)
|
): # 返回一个指数较低但大小相同的数(即返回一个同值的,但指数较低的EncryptedNumber)
|
||||||
if new_exp > self.exponent:
|
if new_exp > self.exponent:
|
||||||
raise ValueError("新指数值 %i 应比原指数 %i 小! " % (new_exp, self.exponent))
|
raise ValueError(
|
||||||
|
"新指数值 %i 应比原指数 %i 小! " % (new_exp, self.exponent)
|
||||||
|
)
|
||||||
|
|
||||||
multiplied = self * pow(EncodedNumber.BASE, self.exponent - new_exp) # 降指数后的乘积
|
multiplied = self * pow(
|
||||||
|
EncodedNumber.BASE, self.exponent - new_exp
|
||||||
|
) # 降指数后的乘积
|
||||||
multiplied.exponent = new_exp # 降指数后的新指数
|
multiplied.exponent = new_exp # 降指数后的新指数
|
||||||
return multiplied
|
return multiplied
|
||||||
|
|
||||||
@ -349,7 +376,9 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
b.encoding, 1
|
b.encoding, 1
|
||||||
) # 用公钥加密b.encoding后的标量
|
) # 用公钥加密b.encoding后的标量
|
||||||
|
|
||||||
sum_ciphertext = a._raw_add(a.ciphertext(False), encrypted_scalar) # 进行相加操作
|
sum_ciphertext = a._raw_add(
|
||||||
|
a.ciphertext(False), encrypted_scalar
|
||||||
|
) # 进行相加操作
|
||||||
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
|
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
|
||||||
|
|
||||||
def _add_encrypted(self, other): # 对EncodedNumber与EncodedNumber加法加密
|
def _add_encrypted(self, other): # 对EncodedNumber与EncodedNumber加法加密
|
||||||
@ -396,8 +425,12 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
result = 0 # 将初始值设置为0
|
result = 0 # 将初始值设置为0
|
||||||
for i in args:
|
for i in args:
|
||||||
if not isinstance(i, (int, float, EncryptedNumber)):
|
if not isinstance(i, (int, float, EncryptedNumber)):
|
||||||
raise TypeError("期望密文应该是int/float/EncryptedNumber型, 而不是 %s" % type(i))
|
raise TypeError(
|
||||||
if isinstance(i, int or float): # 如果是 int 或 float 明文型,则先将明文加密在进行运算
|
"期望密文应该是int/float/EncryptedNumber型, 而不是 %s" % type(i)
|
||||||
|
)
|
||||||
|
if isinstance(
|
||||||
|
i, int or float
|
||||||
|
): # 如果是 int 或 float 明文型,则先将明文加密在进行运算
|
||||||
result += self.public_key.encrypt(i)
|
result += self.public_key.encrypt(i)
|
||||||
else:
|
else:
|
||||||
result += i # 第一次循环:标量与密文相加;后面的循环,密文与密文相加
|
result += i # 第一次循环:标量与密文相加;后面的循环,密文与密文相加
|
||||||
@ -424,7 +457,9 @@ class EncryptedNumber(object): # 浮点数或整数的Pailier加密
|
|||||||
args[2]: 给第一个参数设置的权值
|
args[2]: 给第一个参数设置的权值
|
||||||
。。。。。。
|
。。。。。。
|
||||||
"""
|
"""
|
||||||
total_weight = sum(args[2::2]) # 计算权值的总和(使用切片操作从参数列表中取出索引为参数权值的元素)
|
total_weight = sum(
|
||||||
|
args[2::2]
|
||||||
|
) # 计算权值的总和(使用切片操作从参数列表中取出索引为参数权值的元素)
|
||||||
if total_weight != 1:
|
if total_weight != 1:
|
||||||
raise TypeError("加权平均算法的权值设置错误!请重新设置!")
|
raise TypeError("加权平均算法的权值设置错误!请重新设置!")
|
||||||
else:
|
else:
|
||||||
@ -482,7 +517,9 @@ if __name__ == "__main__": # 主函数
|
|||||||
x_encrypted = Public_Key.encrypt(x) # 加密后的x
|
x_encrypted = Public_Key.encrypt(x) # 加密后的x
|
||||||
y_encrypted = Public_Key.encrypt(y) # 加密后的y
|
y_encrypted = Public_Key.encrypt(y) # 加密后的y
|
||||||
z_encrypted = Public_Key.encrypt(z) # 加密后的z
|
z_encrypted = Public_Key.encrypt(z) # 加密后的z
|
||||||
t_encrypted = x_encrypted + y_encrypted * 0.5 # 在x,y保密的情况下计算t,得到加密后的t(t_encrypted)
|
t_encrypted = (
|
||||||
|
x_encrypted + y_encrypted * 0.5
|
||||||
|
) # 在x,y保密的情况下计算t,得到加密后的t(t_encrypted)
|
||||||
|
|
||||||
# x_encrypted = x_encrypted.increment() # 自增
|
# x_encrypted = x_encrypted.increment() # 自增
|
||||||
# y_encrypted = y_encrypted.decrement() # 自减
|
# y_encrypted = y_encrypted.decrement() # 自减
|
||||||
|
Loading…
x
Reference in New Issue
Block a user