Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_shamir_secret_sharing.py
2587 views
1
import os
2
import sys
3
from hashlib import sha256
4
from random import randrange
5
from unittest import TestCase
6
7
from sage.all import GF
8
9
path = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
10
if sys.path[1] != path:
11
sys.path.insert(1, path)
12
13
from attacks.shamir_secret_sharing import deterministic_coefficients
14
from attacks.shamir_secret_sharing import share_forgery
15
16
17
class TestShamirSecretSharing(TestCase):
18
def _eval(self, p, a, x):
19
y = 0
20
for i, ai in enumerate(a):
21
y += ai * x ** i
22
return y % p
23
24
def test_deterministic_coefficients(self):
25
p = 3615438361
26
k = 15
27
n = 20
28
s = randrange(1, p)
29
f = lambda ai: int.from_bytes(sha256(ai.to_bytes(32, byteorder="big")).digest(), byteorder="big")
30
31
a = [s]
32
for i in range(1, n + 1):
33
a.append(f(a[i - 1]))
34
a = a[:k]
35
36
xs = []
37
ys = []
38
for i in range(n):
39
x = randrange(1, p)
40
xs.append(x)
41
y = self._eval(p, a, x)
42
ys.append(y)
43
44
s_ = deterministic_coefficients.attack(p, k, a[1], f, xs[0], ys[0])
45
self.assertIsInstance(s_, int)
46
self.assertEqual(s_, s)
47
48
def test_share_forgery(self):
49
p = 4224273359
50
k = 15
51
n = 20
52
s = randrange(1, p)
53
s_ = randrange(1, p)
54
55
a = [s]
56
for i in range(1, n + 1):
57
a.append(randrange(1, p))
58
a = a[:k]
59
60
xs = []
61
ys = []
62
for i in range(n):
63
x = randrange(1, p)
64
xs.append(x)
65
y = self._eval(p, a, x)
66
ys.append(y)
67
68
ys[0] = share_forgery.attack(p, s, s_, xs[0], ys[0], xs[1:])
69
self.assertIsInstance(ys[0], int)
70
self.assertEqual(s_, GF(p)["x"].lagrange_polynomial(zip(xs, ys)).constant_coefficient())
71
72