Debian Codegraph @

lib/Crypto/Protocol/SecretSharing.py

raw symbols SCIP
1 #
2 # SecretSharing.py : distribute a secret amongst a group of participants
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 from Crypto.Util.py3compat import is_native_int
35 from Crypto.Util import number
36 from Crypto.Util.number import long_to_bytes, bytes_to_long
37 from Crypto.Random import get_random_bytes as rng
38
39
40 def _mult_gf2(f1, f2):
41 """Multiply two polynomials in GF(2)"""
42
43 # Ensure f2 is the smallest
44 if f2 > f1:
45 f1, f2 = f2, f1
46 z = 0
47 while f2:
48 if f2 & 1:
49 z ^= f1
50 f1 <<= 1
51 f2 >>= 1
52 return z
53
54
55 def _div_gf2(a, b):
56 """
57 Compute division of polynomials over GF(2).
58 Given a and b, it finds two polynomials q and r such that:
59
60 a = b*q + r with deg(r)<deg(b)
61 """
62
63 if (a < b):
64 return 0, a
65
66 deg = number.size
67 q = 0
68 r = a
69 d = deg(b)
70 while deg(r) >= d:
71 s = 1 << (deg(r) - d)
72 q ^= s
73 r ^= _mult_gf2(b, s)
74 return (q, r)
75
76
77 class _Element(object):
78 """Element of GF(2^128) field"""
79
80 # The irreducible polynomial defining this field is 1+x+x^2+x^7+x^128
81 irr_poly = 1 + 2 + 4 + 128 + 2 ** 128
82
83 def __init__(self, encoded_value):
84 """Initialize the element to a certain value.
85
86 The value passed as parameter is internally encoded as
87 a 128-bit integer, where each bit represents a polynomial
88 coefficient. The LSB is the constant coefficient.
89 """
90
91 if is_native_int(encoded_value):
92 self._value = encoded_value
93 elif len(encoded_value) == 16:
94 self._value = bytes_to_long(encoded_value)
95 else:
96 raise ValueError("The encoded value must be an integer or a 16 byte string")
97
98 def __eq__(self, other):
99 return self._value == other._value
100
101 def __int__(self):
102 """Return the field element, encoded as a 128-bit integer."""
103 return self._value
104
105 def encode(self):
106 """Return the field element, encoded as a 16 byte string."""
107 return long_to_bytes(self._value, 16)
108
109 def __mul__(self, factor):
110
111 f1 = self._value
112 f2 = factor._value
113
114 # Make sure that f2 is the smallest, to speed up the loop
115 if f2 > f1:
116 f1, f2 = f2, f1
117
118 if self.irr_poly in (f1, f2):
119 return _Element(0)
120
121 mask1 = 2 ** 128
122 v, z = f1, 0
123 while f2:
124 # if f2 ^ 1: z ^= v
125 mask2 = int(bin(f2 & 1)[2:] * 128, base=2)
126 z = (mask2 & (z ^ v)) | ((mask1 - mask2 - 1) & z)
127 v <<= 1
128 # if v & mask1: v ^= self.irr_poly
129 mask3 = int(bin((v >> 128) & 1)[2:] * 128, base=2)
130 v = (mask3 & (v ^ self.irr_poly)) | ((mask1 - mask3 - 1) & v)
131 f2 >>= 1
132 return _Element(z)
133
134 def __add__(self, term):
135 return _Element(self._value ^ term._value)
136
137 def inverse(self):
138 """Return the inverse of this element in GF(2^128)."""
139
140 # We use the Extended GCD algorithm
141 # http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor
142
143 if self._value == 0:
144 raise ValueError("Inversion of zero")
145
146 r0, r1 = self._value, self.irr_poly
147 s0, s1 = 1, 0
148 while r1 > 0:
149 q = _div_gf2(r0, r1)[0]
150 r0, r1 = r1, r0 ^ _mult_gf2(q, r1)
151 s0, s1 = s1, s0 ^ _mult_gf2(q, s1)
152 return _Element(s0)
153
154 def __pow__(self, exponent):
155 result = _Element(self._value)
156 for _ in range(exponent - 1):
157 result = result * self
158 return result
159
160
161 class Shamir(object):
162 """Shamir's secret sharing scheme.
163
164 A secret is split into ``n`` shares, and it is sufficient to collect
165 ``k`` of them to reconstruct the secret.
166 """
167
168 @staticmethod
169 def split(k, n, secret, ssss=False):
170 """Split a secret into ``n`` shares.
171
172 The secret can be reconstructed later using just ``k`` shares
173 out of the original ``n``.
174 Each share must be kept confidential to the person it was
175 assigned to.
176
177 Each share is associated to an index (starting from 1).
178
179 Args:
180 k (integer):
181 The sufficient number of shares to reconstruct the secret (``k < n``).
182 n (integer):
183 The number of shares that this method will create.
184 secret (byte string):
185 A byte string of 16 bytes (e.g. the AES 128 key).
186 ssss (bool):
187 If ``True``, the shares can be used with the ``ssss`` utility.
188 Default: ``False``.
189
190 Return (tuples):
191 ``n`` tuples. A tuple is meant for each participant and it contains two items:
192
193 1. the unique index (an integer)
194 2. the share (a byte string, 16 bytes)
195 """
196
197 #
198 # We create a polynomial with random coefficients in GF(2^128):
199 #
200 # p(x) = \sum_{i=0}^{k-1} c_i * x^i
201 #
202 # c_0 is the encoded secret
203 #
204
205 coeffs = [_Element(rng(16)) for i in range(k - 1)]
206 coeffs.append(_Element(secret))
207
208 # Each share is y_i = p(x_i) where x_i is the public index
209 # associated to each of the n users.
210
211 def make_share(user, coeffs, ssss):
212 idx = _Element(user)
213 share = _Element(0)
214 for coeff in coeffs:
215 share = idx * share + coeff
216 if ssss:
217 share += _Element(user) ** len(coeffs)
218 return share.encode()
219
220 return [(i, make_share(i, coeffs, ssss)) for i in range(1, n + 1)]
221
222 @staticmethod
223 def combine(shares, ssss=False):
224 """Recombine a secret, if enough shares are presented.
225
226 Args:
227 shares (tuples):
228 The *k* tuples, each containin the index (an integer) and
229 the share (a byte string, 16 bytes long) that were assigned to
230 a participant.
231 ssss (bool):
232 If ``True``, the shares were produced by the ``ssss`` utility.
233 Default: ``False``.
234
235 Return:
236 The original secret, as a byte string (16 bytes long).
237 """
238
239 #
240 # Given k points (x,y), the interpolation polynomial of degree k-1 is:
241 #
242 # L(x) = \sum_{j=0}^{k-1} y_i * l_j(x)
243 #
244 # where:
245 #
246 # l_j(x) = \prod_{ \overset{0 \le m \le k-1}{m \ne j} }
247 # \frac{x - x_m}{x_j - x_m}
248 #
249 # However, in this case we are purely interested in the constant
250 # coefficient of L(x).
251 #
252
253 k = len(shares)
254
255 gf_shares = []
256 for x in shares:
257 idx = _Element(x[0])
258 value = _Element(x[1])
259 if any(y[0] == idx for y in gf_shares):
260 raise ValueError("Duplicate share")
261 if ssss:
262 value += idx ** k
263 gf_shares.append((idx, value))
264
265 result = _Element(0)
266 for j in range(k):
267 x_j, y_j = gf_shares[j]
268
269 numerator = _Element(1)
270 denominator = _Element(1)
271
272 for m in range(k):
273 x_m = gf_shares[m][0]
274 if m != j:
275 numerator *= x_m
276 denominator *= x_j + x_m
277 result += y_j * numerator * denominator.inverse()
278 return result.encode()