A Pure Python implementation of Shamir's Secret Sharing
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
9.1 KiB

  1. # Copyright 2023 John-Mark Gurney.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions
  5. # are met:
  6. # 1. Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # 2. Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. #
  12. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  13. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  15. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  16. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  17. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  18. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  19. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  20. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  21. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22. # SUCH DAMAGE.
  23. #
  24. import functools
  25. import operator
  26. import random
  27. import unittest.mock
  28. def _makered(x, y):
  29. '''Make reduction table entry.
  30. given x * 2^8, reduce it assuming polynomial y.
  31. '''
  32. x = x << 8
  33. for i in range(3, -1, -1):
  34. if x & (1 << (i + 8)):
  35. x ^= (0x100 + y) << i
  36. assert x < 256
  37. return x
  38. def evalpoly(polynomial, powers):
  39. return sum(( x * y for x, y in zip(polynomial, powers)), 0)
  40. def create_shares(data, k, nshares):
  41. '''Given data, create nshares, such that given any k shares,
  42. data can be recovered.
  43. data must be bytes, or able to be converted to bytes.
  44. The return value will be a list of length nshares. Each element
  45. will be a tuple of (<int in range [1, nshares + 1)>, <bytes>).'''
  46. data = bytes(data)
  47. powers = { x: GF2p8(x).powerseries(k - 1) for x in range(1, nshares + 1) }
  48. coeffs = [ [ x ] + [ random.randint(1, 255) for y in range(k - 1) ] for idx, x in enumerate(data) ]
  49. return [ (x, bytes([ int(evalpoly(coeffs[idx], powers[x])) for idx, val in enumerate(data) ])) for x in range(1, nshares + 1) ]
  50. def recover_data(shares, k):
  51. '''Recover the value given shares, where k is needed.
  52. shares must be as least length of k.'''
  53. if len(shares) < k:
  54. raise ValueError('not enough shares to recover')
  55. return bytes([ int(sum([ GF2p8(y[idx]) *
  56. functools.reduce(operator.mul, [ pix * ((GF2p8(pix) - x) ** -1) for
  57. pix, piy in shares[:k] if pix != x ], 1) for x, y in shares[:k] ],
  58. 0)) for idx in range(len(shares[0][1]))])
  59. class GF2p8:
  60. _invcache = {1: 1, 2: 195, 3: 130, 4: 162, 5: 126, 6: 65, 7: 90, 8: 81, 9: 54, 10: 63, 11: 172, 12: 227, 13: 104, 14: 45, 15: 42, 16: 235, 17: 155, 18: 27, 19: 53, 20: 220, 21: 30, 22: 86, 23: 165, 24: 178, 25: 116, 26: 52, 27: 18, 28: 213, 29: 100, 30: 21, 31: 221, 32: 182, 33: 75, 34: 142, 35: 251, 36: 206, 37: 233, 38: 217, 39: 161, 40: 110, 41: 219, 42: 15, 43: 44, 44: 43, 45: 14, 46: 145, 47: 241, 48: 89, 49: 215, 50: 58, 51: 244, 52: 26, 53: 19, 54: 9, 55: 80, 56: 169, 57: 99, 58: 50, 59: 245, 60: 201, 61: 204, 62: 173, 63: 10, 64: 91, 65: 6, 66: 230, 67: 247, 68: 71, 69: 191, 70: 190, 71: 68, 72: 103, 73: 123, 74: 183, 75: 33, 76: 175, 77: 83, 78: 147, 79: 255, 80: 55, 81: 8, 82: 174, 83: 77, 84: 196, 85: 209, 86: 22, 87: 164, 88: 214, 89: 48, 90: 7, 91: 64, 92: 139, 93: 157, 94: 187, 95: 140, 96: 239, 97: 129, 98: 168, 99: 57, 100: 29, 101: 212, 102: 122, 103: 72, 104: 13, 105: 226, 106: 202, 107: 176, 108: 199, 109: 222, 110: 40, 111: 218, 112: 151, 113: 210, 114: 242, 115: 132, 116: 25, 117: 179, 118: 185, 119: 135, 120: 167, 121: 228, 122: 102, 123: 73, 124: 149, 125: 153, 126: 5, 127: 163, 128: 238, 129: 97, 130: 3, 131: 194, 132: 115, 133: 243, 134: 184, 135: 119, 136: 224, 137: 248, 138: 156, 139: 92, 140: 95, 141: 186, 142: 34, 143: 250, 144: 240, 145: 46, 146: 254, 147: 78, 148: 152, 149: 124, 150: 211, 151: 112, 152: 148, 153: 125, 154: 234, 155: 17, 156: 138, 157: 93, 158: 188, 159: 236, 160: 216, 161: 39, 162: 4, 163: 127, 164: 87, 165: 23, 166: 229, 167: 120, 168: 98, 169: 56, 170: 171, 171: 170, 172: 11, 173: 62, 174: 82, 175: 76, 176: 107, 177: 203, 178: 24, 179: 117, 180: 192, 181: 253, 182: 32, 183: 74, 184: 134, 185: 118, 186: 141, 187: 94, 188: 158, 189: 237, 190: 70, 191: 69, 192: 180, 193: 252, 194: 131, 195: 2, 196: 84, 197: 208, 198: 223, 199: 108, 200: 205, 201: 60, 202: 106, 203: 177, 204: 61, 205: 200, 206: 36, 207: 232, 208: 197, 209: 85, 210: 113, 211: 150, 212: 101, 213: 28, 214: 88, 215: 49, 216: 160, 217: 38, 218: 111, 219: 41, 220: 20, 221: 31, 222: 109, 223: 198, 224: 136, 225: 249, 226: 105, 227: 12, 228: 121, 229: 166, 230: 66, 231: 246, 232: 207, 233: 37, 234: 154, 235: 16, 236: 159, 237: 189, 238: 128, 239: 96, 240: 144, 241: 47, 242: 114, 243: 133, 244: 51, 245: 59, 246: 231, 247: 67, 248: 137, 249: 225, 250: 143, 251: 35, 252: 193, 253: 181, 254: 146, 255: 79}
  61. @staticmethod
  62. def _primativemul(a, b):
  63. masks = [ 0, 0xff ]
  64. r = 0
  65. for i in range(0, 8):
  66. mask = a & 1
  67. r ^= (masks[mask] & b) << i
  68. a = a >> 1
  69. return r
  70. # polynomial 0x187
  71. _reduce = { x: _makered(x, 0x87) for x in range(0, 16) }
  72. def __init__(self, v):
  73. if v >= 256:
  74. raise ValueError('%d is not a member of GF(2^8)' % v)
  75. self._v = v
  76. # basic operations
  77. def __add__(self, o):
  78. if isinstance(o, int):
  79. return self + self.__class__(o)
  80. return self.__class__(self._v ^ o._v)
  81. def __radd__(self, o):
  82. return self.__add__(o)
  83. def __sub__(self, o):
  84. return self.__add__(o)
  85. def __rsub__(self, o):
  86. return self.__sub__(o)
  87. def __mul__(self, o):
  88. if isinstance(o, int):
  89. o = self.__class__(o)
  90. m = o._v
  91. # multiply
  92. r = self._primativemul(self._v, m)
  93. # reduce
  94. r ^= self._reduce[r >> 12] << 4
  95. r ^= self._reduce[(r >> 8) & 0xf ]
  96. r &= 0xff
  97. return self.__class__(r)
  98. def __rmul__(self, o):
  99. return self.__mul__(o)
  100. def __pow__(self, x):
  101. if x == -1 and self._invcache:
  102. return GF2p8(self._invcache[self._v])
  103. if x < 0:
  104. x += 255
  105. v = self.__class__(1)
  106. # TODO - make faster via caching and squaring
  107. for i in range(x):
  108. v *= self
  109. return v
  110. def powerseries(self, cnt):
  111. '''Generate [ self ** 0, self ** 1, ..., self ** cnt ].'''
  112. r = [ 1 ]
  113. if cnt > 0:
  114. r.append(self)
  115. for i in range(2, cnt):
  116. r.append(r[-1] * self)
  117. return r
  118. def __eq__(self, o):
  119. if isinstance(o, int):
  120. return self._v == o
  121. return self._v == o._v
  122. def __int__(self):
  123. return self._v
  124. def __repr__(self):
  125. return '%s(%d)' % (self.__class__.__name__, self._v)
  126. class TestShamirSS(unittest.TestCase):
  127. def test_evalpoly(self):
  128. a = GF2p8(random.randint(0, 255))
  129. powers = a.powerseries(5)
  130. vals = [ GF2p8(random.randint(0, 255)) for x in range(5) ]
  131. r = evalpoly(vals, powers)
  132. self.assertEqual(r, vals[0] + vals[1] * powers[1] + vals[2] * powers[2] + vals[3] * powers[3] + vals[4] * powers[4])
  133. r = evalpoly(vals[:3], powers)
  134. self.assertEqual(r, vals[0] + vals[1] * powers[1] + vals[2] * powers[2])
  135. def test_create_shares(self):
  136. self.assertRaises(TypeError, create_shares, '', 1, 1)
  137. val = bytes([ random.randint(0, 255) for x in range(100) ])
  138. a = create_shares(val, 2, 3)
  139. # that it has the number of shares
  140. self.assertEqual(len(a), 3)
  141. # that the length of the share data matches passed in data
  142. self.assertEqual(len(a[0][1]), len(val))
  143. # that one share isn't enough
  144. self.assertRaises(ValueError, recover_data, [ a[0] ], 2)
  145. self.assertEqual(val, recover_data(a[:2], 2))
  146. def test_gf2p8_inv(self):
  147. a = GF2p8(random.randint(0, 255))
  148. with unittest.mock.patch.object(GF2p8, '_invcache', {}) as pinvc:
  149. ainv = a ** -1
  150. self.assertEqual(a * ainv, 1)
  151. invcache = { x: int(GF2p8(x) ** -1) for x in range(1, 256) }
  152. if GF2p8._invcache != invcache:
  153. print('inv cache:', repr(invcache))
  154. self.assertEqual(GF2p8._invcache, invcache)
  155. def test_gf2p8_power(self):
  156. a = GF2p8(random.randint(0, 255))
  157. v = GF2p8(1)
  158. for i in range(10):
  159. self.assertEqual(a ** i, v)
  160. v = v * a
  161. for i in range(10):
  162. a = GF2p8(random.randint(0, 255))
  163. powers = a.powerseries(10)
  164. for j in range(10):
  165. self.assertEqual(powers[j], a ** j)
  166. def test_gf2p8(self):
  167. for i in range(10):
  168. a = GF2p8(random.randint(0, 255))
  169. b = GF2p8(random.randint(0, 255))
  170. c = GF2p8(random.randint(0, 255))
  171. self.assertEqual(a * 0, 0)
  172. # Identity
  173. self.assertEqual(a + 0, a)
  174. self.assertEqual(a * 1, a)
  175. self.assertEqual(0 + a, a)
  176. self.assertEqual(1 * a, a)
  177. self.assertEqual(0 - a, a)
  178. # Associativity
  179. self.assertEqual((a + b) + c, a + (b + c))
  180. self.assertEqual((a * b) * c, a * (b * c))
  181. # Communitative
  182. self.assertEqual(a + b, b + a)
  183. self.assertEqual(a * b, b * a)
  184. # Distributive
  185. self.assertEqual(a * (b + c), a * b + a * c)
  186. self.assertEqual((b + c) * a, b * a + c * a)
  187. # Basic mul
  188. self.assertEqual(GF2p8(0x80) * 2, 0x87)
  189. self.assertEqual(GF2p8(0x80) * 6, (0x80 * 6) ^ (0x187 << 1))
  190. self.assertEqual(GF2p8(0x80) * 8, (0x80 * 8) ^ (0x187 << 2) ^ (0x187 << 1) ^ 0x187)
  191. self.assertEqual(a + b - b, a)