SecretSharing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #
  2. # SecretSharing.py : distribute a secret amongst a group of participants
  3. #
  4. # ===================================================================
  5. #
  6. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  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. from Crypto.Util.py3compat import *
  34. from Crypto.Util import number
  35. from Crypto.Util.number import long_to_bytes, bytes_to_long
  36. from Crypto.Random import get_random_bytes as rng
  37. def _mult_gf2(f1, f2):
  38. """Multiply two polynomials in GF(2)"""
  39. # Ensure f2 is the smallest
  40. if f2 > f1:
  41. f1, f2 = f2, f1
  42. z = 0
  43. while f2:
  44. if f2 & 1:
  45. z ^= f1
  46. f1 <<= 1
  47. f2 >>= 1
  48. return z
  49. def _div_gf2(a, b):
  50. """
  51. Compute division of polynomials over GF(2).
  52. Given a and b, it finds two polynomials q and r such that:
  53. a = b*q + r with deg(r)<deg(b)
  54. """
  55. if (a < b):
  56. return 0, a
  57. deg = number.size
  58. q = 0
  59. r = a
  60. d = deg(b)
  61. while deg(r) >= d:
  62. s = 1 << (deg(r) - d)
  63. q ^= s
  64. r ^= _mult_gf2(b, s)
  65. return (q, r)
  66. class _Element(object):
  67. """Element of GF(2^128) field"""
  68. # The irreducible polynomial defining this field is 1+x+x^2+x^7+x^128
  69. irr_poly = 1 + 2 + 4 + 128 + 2 ** 128
  70. def __init__(self, encoded_value):
  71. """Initialize the element to a certain value.
  72. The value passed as parameter is internally encoded as
  73. a 128-bit integer, where each bit represents a polynomial
  74. coefficient. The LSB is the constant coefficient.
  75. """
  76. if isinstance(encoded_value, (int, long)):
  77. self._value = encoded_value
  78. elif len(encoded_value) == 16:
  79. self._value = bytes_to_long(encoded_value)
  80. else:
  81. raise ValueError("The encoded value must be an integer or a 16 byte string")
  82. def __int__(self):
  83. """Return the field element, encoded as a 128-bit integer."""
  84. return self._value
  85. def encode(self):
  86. """Return the field element, encoded as a 16 byte string."""
  87. return long_to_bytes(self._value, 16)
  88. def __mul__(self, factor):
  89. f1 = self._value
  90. f2 = factor._value
  91. # Make sure that f2 is the smallest, to speed up the loop
  92. if f2 > f1:
  93. f1, f2 = f2, f1
  94. if self.irr_poly in (f1, f2):
  95. return _Element(0)
  96. mask1 = 2 ** 128
  97. v, z = f1, 0
  98. while f2:
  99. if f2 & 1:
  100. z ^= v
  101. v <<= 1
  102. if v & mask1:
  103. v ^= self.irr_poly
  104. f2 >>= 1
  105. return _Element(z)
  106. def __add__(self, term):
  107. return _Element(self._value ^ term._value)
  108. def inverse(self):
  109. """Return the inverse of this element in GF(2^128)."""
  110. # We use the Extended GCD algorithm
  111. # http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor
  112. r0, r1 = self._value, self.irr_poly
  113. s0, s1 = 1, 0
  114. while r1 > 0:
  115. q = _div_gf2(r0, r1)[0]
  116. r0, r1 = r1, r0 ^ _mult_gf2(q, r1)
  117. s0, s1 = s1, s0 ^ _mult_gf2(q, s1)
  118. return _Element(s0)
  119. class Shamir(object):
  120. """Shamir's secret sharing scheme.
  121. This class implements the Shamir's secret sharing protocol
  122. described in his original paper `"How to share a secret"`__.
  123. All shares are points over a 2-dimensional curve. At least
  124. *k* points (that is, shares) are required to reconstruct the curve,
  125. and therefore the secret.
  126. This implementation is primarilly meant to protect AES128 keys.
  127. To that end, the secret is associated to a curve in
  128. the field GF(2^128) defined by the irreducible polynomial
  129. :math:`x^{128} + x^7 + x^2 + x + 1` (the same used in AES-GCM).
  130. The shares are always 16 bytes long.
  131. Data produced by this implementation are compatible to the popular
  132. `ssss`_ tool if used with 128 bit security (parameter *"-s 128"*)
  133. and no dispersion (parameter *"-D"*).
  134. As an example, the following code shows how to protect a file meant
  135. for 5 people, in such a way that 2 of the 5 are required to
  136. reassemble it::
  137. >>> from binascii import hexlify
  138. >>> from Crypto.Cipher import AES
  139. >>> from Crypto.Random import get_random_bytes
  140. >>> from Crypto.Protocol.secret_sharing import Shamir
  141. >>>
  142. >>> key = get_random_bytes(16)
  143. >>> shares = Shamir.split(2, 5, key)
  144. >>> for idx, share in shares:
  145. >>> print "Index #%d: %s" % (idx, hexlify(share))
  146. >>>
  147. >>> fi = open("clear_file.txt", "rb")
  148. >>> fo = open("enc_file.txt", "wb")
  149. >>>
  150. >>> cipher = AES.new(key, AES.MODE_EAX)
  151. >>> ct, tag = cipher.encrypt(fi.read()), cipher.digest()
  152. >>> fo.write(nonce + tag + ct)
  153. Each person can be given one share and the encrypted file.
  154. When 2 people gather together with their shares, the can
  155. decrypt the file::
  156. >>> from binascii import unhexlify
  157. >>> from Crypto.Cipher import AES
  158. >>> from Crypto.Protocol.secret_sharing import Shamir
  159. >>>
  160. >>> shares = []
  161. >>> for x in range(2):
  162. >>> in_str = raw_input("Enter index and share separated by comma: ")
  163. >>> idx, share = [ strip(s) for s in in_str.split(",") ]
  164. >>> shares.append((idx, unhexlify(share)))
  165. >>> key = Shamir.combine(shares)
  166. >>>
  167. >>> fi = open("enc_file.txt", "rb")
  168. >>> nonce, tag = [ fi.read(16) for x in range(2) ]
  169. >>> cipher = AES.new(key, AES.MODE_EAX, nonce)
  170. >>> try:
  171. >>> result = cipher.decrypt(fi.read())
  172. >>> cipher.verify(tag)
  173. >>> with open("clear_file2.txt", "wb") as fo:
  174. >>> fo.write(result)
  175. >>> except ValueError:
  176. >>> print "The shares were incorrect"
  177. .. attention::
  178. Reconstruction does not guarantee that the result is authentic.
  179. In particular, a malicious participant in the scheme has the
  180. ability to force an algebric transformation on the result by
  181. manipulating her share.
  182. It is important to use the scheme in combination with an
  183. authentication mechanism (the EAX cipher mode in the example).
  184. .. __: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.80.8910&rep=rep1&type=pdf
  185. .. _ssss: http://point-at-infinity.org/ssss/
  186. """
  187. @staticmethod
  188. def split(k, n, secret):
  189. """Split a secret into *n* shares.
  190. The secret can be reconstructed later when *k* shares
  191. out of the original *n* are recombined. Each share
  192. must be kept confidential to the person it was
  193. assigned to.
  194. Each share is associated to an index (starting from 1),
  195. which must be presented when the secret is recombined.
  196. Args:
  197. k (integer):
  198. The number of shares that must be present in order to reconstruct
  199. the secret.
  200. n (integer):
  201. The total number of shares to create (larger than *k*).
  202. secret (byte string):
  203. The 16 byte string (e.g. the AES128 key) to split.
  204. Return:
  205. *n* tuples, each containing the unique index (an integer) and
  206. the share (a byte string, 16 bytes long) meant for a
  207. participant.
  208. """
  209. #
  210. # We create a polynomial with random coefficients in GF(2^128):
  211. #
  212. # p(x) = \sum_{i=0}^{k-1} c_i * x^i
  213. #
  214. # c_0 is the encoded secret
  215. #
  216. coeffs = [_Element(rng(16)) for i in xrange(k - 1)]
  217. coeffs.insert(0, _Element(secret))
  218. # Each share is y_i = p(x_i) where x_i is the public index
  219. # associated to each of the n users.
  220. def make_share(user, coeffs):
  221. share, x, idx = [_Element(p) for p in (0, 1, user)]
  222. for coeff in coeffs:
  223. share += coeff * x
  224. x *= idx
  225. return share.encode()
  226. return [(i, make_share(i, coeffs)) for i in xrange(1, n + 1)]
  227. @staticmethod
  228. def combine(shares):
  229. """Recombine a secret, if enough shares are presented.
  230. Args:
  231. shares (tuples):
  232. At least *k* tuples, each containin the index (an integer) and
  233. the share (a byte string, 16 bytes long) that were assigned to
  234. a participant.
  235. Return:
  236. The original secret, as a byte string (16 bytes long).
  237. """
  238. #
  239. # Given k points (x,y), the interpolation polynomial of degree k-1 is:
  240. #
  241. # L(x) = \sum_{j=0}^{k-1} y_i * l_j(x)
  242. #
  243. # where:
  244. #
  245. # l_j(x) = \prod_{ \overset{0 \le m \le k-1}{m \ne j} }
  246. # \frac{x - x_m}{x_j - x_m}
  247. #
  248. # However, in this case we are purely intersted in the constant
  249. # coefficient of L(x).
  250. #
  251. shares = [[_Element(y) for y in x] for x in shares]
  252. result = _Element(0)
  253. k = len(shares)
  254. for j in xrange(k):
  255. x_j, y_j = shares[j]
  256. coeff_0_l = _Element(0)
  257. while not int(coeff_0_l):
  258. coeff_0_l = _Element(rng(16))
  259. inv = coeff_0_l.inverse()
  260. for m in xrange(k):
  261. x_m = shares[m][0]
  262. if m != j:
  263. t = x_m * (x_j + x_m).inverse()
  264. coeff_0_l *= t
  265. result += y_j * coeff_0_l * inv
  266. return result.encode()