Changeset - d5f60adc56c0
[Not reviewed]
Merge default
0 3 0
Laman - 4 years ago 2020-12-18 12:24:54

merged caching
3 files changed with 5 insertions and 1 deletions:
0 comments (0 inline, 0 general)
src/shamira/benchmark.py
Show inline comments
 
import cProfile
 
import timeit
 

	
 
from . import generate, reconstruct
 
from .tests.test_shamira import TestShamira
 

	
 

	
 
def measure(args):
 
	secret = "1234567890123456"
 
	shares = generate(secret, args.k, args.n)
 
	symbols = globals()
 
	symbols.update(locals())
 

	
 
	time = timeit.timeit("""generate(secret, args.k, args.n)""", number=1, globals=symbols)
 
	print("The generation took {0:.3}s, {1:.3}s per byte.".format(time, time/16))
 

	
 
	time = timeit.timeit("""reconstruct(*shares)""", number=1, globals=symbols)
 
	print("The reconstruction took {0:.3}s, {1:.3}s per byte.".format(time, time/16))
 

	
 

	
 
def profile(args):
 
	t = TestShamira()
 

	
 
	cProfile.runctx(r"""t.test_generate_reconstruct()""", globals=globals(), locals=locals())
 
	cProfile.runctx(r"""t.test_generate_reconstruct()""", globals=globals(), locals=locals(), sort="cumtime")
 

	
 

	
 
def build_subparsers(parent):
 
	parent.set_defaults(func=lambda _: parent.error("missing command"))
 
	subparsers = parent.add_subparsers()
 

	
 
	profile_parser = subparsers.add_parser("profile")
 
	profile_parser.set_defaults(func=profile)
 

	
 
	measure_parser = subparsers.add_parser("measure")
 
	measure_parser.add_argument("-k", type=int, required=True)
 
	measure_parser.add_argument("-n", type=int, required=True)
 
	measure_parser.set_defaults(func=measure)
src/shamira/fft.py
Show inline comments
 
import math
 
import cmath
 
import itertools
 
from functools import cache
 

	
 
from .gf256 import gfmul, gfpow
 

	
 
# divisors of 255 and their factors in natural numbers
 
DIVISORS = [3, 5, 15, 17, 51, 85, 255]
 
FACTORS = {3: [3], 5: [5], 15: [3, 5], 17: [17], 51: [3, 17], 85: [5, 17], 255: [3, 5, 17]}
 
# values of n-th square roots in GF256
 
SQUARE_ROOTS = {3: 189, 5: 12, 15: 225, 17: 53, 51: 51, 85: 15, 255: 3}
 

	
 

	
 
def ceil_size(n):
 
	assert n <= DIVISORS[-1]
 
	for (i, ni) in enumerate(DIVISORS):
 
		if ni >= n:
 
			break
 

	
 
	return ni
 

	
 

	
 
@cache
 
def precompute_x(n):
 
	"""Return a geometric sequence [1, w, w**2, ..., w**(n-1)], where w**n==1.
 
	This can be done only for certain values of n."""
 
	assert n in SQUARE_ROOTS, n
 
	w = SQUARE_ROOTS[n]  # primitive N-th square root of 1
 
	return list(itertools.accumulate([1]+[w]*(n-1), gfmul))
 

	
 

	
 
def complex_dft(p):
 
	"""Quadratic formula from the definition. The basic case in complex numbers."""
 
	N = len(p)
 
	w = cmath.exp(-2*math.pi*1j/N)  # primitive N-th square root of 1
 
	y = [0]*N
 
	for k in range(N):
 
		xk = w**k
 
		for n in range(N):
 
			y[k] += p[n] * xk**n
 
	return y
 

	
 

	
 
def dft(p):
 
	"""Quadratic formula from the definition. In GF256."""
 
	N = len(p)
 
	x = precompute_x(N)
 
	y = [0]*N
 
	for k in range(N):
 
		for n in range(N):
 
			y[k] ^= gfmul(p[n], gfpow(x[k], n))
 
	return y
 

	
 

	
 
def compute_inverse(N1, N2):
 
	for i in range(N2):
 
		if N1*i % N2 == 1:
 
			return i
 
	raise ValueError("Failed to find an inverse to {0} mod {1}.".format(N1, N2))
 

	
 

	
 
def prime_fft(p, divisors, basic_dft=dft):
 
	"""https://en.wikipedia.org/wiki/Prime-factor_FFT_algorithm"""
 
	if len(divisors) == 1:
 
		return basic_dft(p)
 
	N = len(p)
 
	N1 = divisors[0]
 
	N2 = N//N1
 
	N1_inv = compute_inverse(N1, N2)
 
	N2_inv = compute_inverse(N2, N1)
 

	
src/shamira/gf256.py
Show inline comments
 
# GNU GPLv3, see LICENSE
 

	
 
"""Arithmetic operations on Galois Field 2**8. See https://en.wikipedia.org/wiki/Finite_field_arithmetic"""
 

	
 
from functools import reduce, cache
 
import operator
 

	
 

	
 
def _gfmul(a, b):
 
	"""Basic multiplication. Russian peasant algorithm."""
 
	res = 0
 
	while a and b:
 
		if b&1: res ^= a
 
		if a&0x80: a = 0xff&(a<<1)^0x1b
 
		else: a <<= 1
 
		b >>= 1
 
	return res
 

	
 

	
 
g = 3  # generator
 
E = [None]*256  # exponentials
 
L = [None]*256  # logarithms
 
acc = 1
 
for i in range(256):
 
	E[i] = acc
 
	L[acc] = i
 
	acc = _gfmul(acc, g)
 
L[1] = 0
 
INV = [E[255-L[i]] if i!=0 else None for i in range(256)]  # multiplicative inverse
 

	
 

	
 
@cache
 
def gfmul(a, b):
 
	"""Fast multiplication. Basic multiplication is expensive. a*b==g**(log(a)+log(b))"""
 
	assert 0<=a<=255, 0<=b<=255
 
	if a==0 or b==0: return 0
 
	t = L[a]+L[b]
 
	if t>255: t -= 255
 
	return E[t]
 

	
 

	
 
@cache
 
def gfpow(x, k):
 
	"""Compute x**k."""
 
	i = 1
 
	res = 1
 
	while i <= k:
 
		if k&i:
 
			res = gfmul(res, x)
 
		x = gfmul(x, x)
 
		i <<= 1
 

	
 
	return res
 

	
 

	
 
def evaluate(coefs, x):
 
	"""Evaluate polynomial's value at x.
 

	
 
	:param coefs: [an, ..., a1, a0]."""
 
	res = 0
 

	
 
	for a in coefs:  # Horner's rule
 
		res = gfmul(res, x)
 
		res ^= a
 

	
 
	return res
 

	
 

	
 
def get_constant_coef(weights, y_coords):
 
	"""Compute constant polynomial coefficient given the points.
 

	
 
	See https://en.wikipedia.org/wiki/Shamir's_Secret_Sharing#Computationally_Efficient_Approach"""
 
	return reduce(
 
		operator.xor,
 
		map(lambda ab: gfmul(*ab), zip(weights, y_coords))
 
	)
 

	
 

	
 
def compute_weights(x_coords):
 
	assert x_coords
 

	
 
	res = [
 
			reduce(
 
				gfmul,
 
				(gfmul(xj, INV[xj^xi]) for xj in x_coords if xi!=xj),
 
				1
 
			) for xi in x_coords
 
	]
 

	
 
	return res
0 comments (0 inline, 0 general)