zoukankan      html  css  js  c++  java
  • python 实现shamir秘密分割和秘密恢复及其加法同态性

    秘密分割:

    #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)
  • 相关阅读:
    消除 transition 闪屏
    解决audio和video在手机端无法自动播放问题
    css3让图文不能复制
    改变placeholder的字体颜色大小
    css3实现水平、垂直居中
    link 和@import 的区别
    JSON与对象的相互转换
    indexOf与includes的比较
    DOM盒子模型
    关于Meta标签的一些知识
  • 原文地址:https://www.cnblogs.com/LLLLgR/p/14876593.html
Copyright © 2011-2022 走看看