秘密分割:
#The following function turns an integer into a number of shares given a modulus and a number of parties. def share(value1, parties, prime, coefficients = None): # if value1 == float('inf'): # print(value1) # print('分解的值:',value1) value = int(value1 * (10**10)) shares = {} threshold = parties - 1 #比总数少两份碎片时即可还原秘密 if coefficients is None: # Random polynomial coefficients. polynomial = [value] + [randint(0,prime-1) for _ in range(1,threshold)] else: polynomial = [value] + coefficients # Compute each share such that shares[i] = f(i). for i in range(1, parties+1): shares[i] = polynomial[0] for j in range(1, len(polynomial)): shares[i] = (shares[i] + polynomial[j] * pow(i,j)) % prime return shares, polynomial
实现秘密的分发:
# 定义分发函数,把shares分给不同的用户 def distribution(shares,shares_index,sensorydata, a_li): list0 = np.arange(1,len(shares)+1) np.random.shuffle(list0) i = 0 for index,item in enumerate(sensorydata): li1 = [a[0] for a in a_li[i]] tmp = [list0[index], shares[list0[index]]] if index != 0: write(tmp) if tmp[0] in li1: ind = li1.index(tmp[0]) a_li[i][ind][1] += tmp[1] % prime else: a_li[i].append(tmp) i += 1 for i in range(len(sensorydata)): a_li[i].sort() if i != 0 : write(a_li) return a_li
实现其加法同态性及秘密恢复:
def recover(a_li): sharelist=[] for index,item in enumerate(a_li): dic = {} final ={} for i in range(len(a_li[index])): dic[a_li[index][i][0]] = a_li[index][i][1] % prime sharelist.append(dic) df = pd.DataFrame(sharelist) result = df.apply(lambda x: x.sum() % prime,axis=0) # 按列相加 # 将最终结果整合为一个合并之后的share for index,item in enumerate(result): final[index+1]=item recovered = interpolate(final, prime) return np.round(recovered/(10**10),7)