Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_elgamal_encryption.py
2587 views
1
import os
2
import sys
3
from random import randrange
4
from unittest import TestCase
5
6
from sage.all import legendre_symbol
7
8
path = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
9
if sys.path[1] != path:
10
sys.path.insert(1, path)
11
12
from attacks.elgamal_encryption import nonce_reuse
13
from attacks.elgamal_encryption import unsafe_generator
14
15
16
class TestElgamalEncryption(TestCase):
17
def test_nonce_reuse(self):
18
# Safe prime.
19
p = 16902648776703029279
20
g = 3
21
for _ in range(100):
22
x = randrange(1, p)
23
h = pow(g, x, p)
24
y = randrange(1, p)
25
s = pow(h, y, p)
26
m = randrange(1, p)
27
c1 = pow(g, y, p)
28
c2 = m * s % p
29
m_ = randrange(1, p)
30
c1_ = pow(g, y, p)
31
c2_ = m_ * s % p
32
m__ = nonce_reuse.attack(p, m, c1, c2, c1_, c2_)
33
self.assertIsInstance(m__, int)
34
self.assertEqual(m_, m__)
35
36
def test_unsafe_generator(self):
37
# Safe prime.
38
p = 16902648776703029279
39
# Unsafe generator, generates the entire group.
40
g = 7
41
for _ in range(100):
42
x = randrange(1, p)
43
h = pow(g, x, p)
44
y = randrange(1, p)
45
s = pow(h, y, p)
46
m = randrange(1, p)
47
c1 = pow(g, y, p)
48
c2 = m * s % p
49
k = unsafe_generator.attack(p, h, c1, c2)
50
self.assertIsInstance(k, int)
51
self.assertEqual(legendre_symbol(m, p), k)
52
53