采用 galois 的python库(https://github.com/mhostetter/galois ),快速写了一个在扩GF(2^m)上的 [t,n] 门限的Shamir-secret-sharing 流程;
document写的也很详细使用起来非常趁手。缺点就是效率略低一些。
https://pypi.org/project/galois/#polynomial-construction
代码如下:
import numpy as npimport galois # Apply GF calculation implement Shamir Secret Share# system parameter# fIEld paramn = 10t = 6F_num = 2**8GF256 = galois.GF(F_num)def distribute_shares(s): # Construct the polynomial and distribute the shares # print('The secret is :',s) powers =[i for i in range(t-1,-1,-1)] coeffs = [np.random.randint(F_num) for _ in range(t-1)] # append the secret as intercept; coeffs.append(s) p = galois.poly.degrees(powers, coeffs, fIEld=GF256) print('construct the polynomials:',p) # randomly generate n points secret_shares =[] xp = np.random.choice(range(F_num),n,replace=False) secret_shares = [str(xi)+'-'+str(int(p(xi).base)) for xi in xp] return secret_sharesdef reconstruct_secret(collected_shares): # reconstruct the secret with collected shares if len(collected_shares) != t: return np.nan x = [] y = [] for item in collected_shares: xi = int(item.split('-')[0]) yi = int(item.split('-')[1]) x.append(xi) y.append(yi) ss_0 = GF256(0) for i in range(t): item = GF256(y[i]) for j in range(t): if i!=j: item *= -1*GF256(x[j])/(GF256(x[i])-GF256(x[j])) ss_0 += item return int(ss_0.base) # generate secret sharessecret_shares = distribute_shares(33)# collect random share collected_shares = np.random.choice(secret_shares,t,replace=False)print('Randomly selected t shares \'x-y\':')print(collected_shares)recon_secret = reconstruct_secret(collected_shares)print('Reconstructed secret:',recon_secret)
总结 以上是内存溢出为你收集整理的用python实现Shamir-secret-share全部内容,希望文章能够帮你解决用python实现Shamir-secret-share所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)