Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_ecb.py
2587 views
1
import os
2
import sys
3
from random import choices
4
from random import randrange
5
from unittest import TestCase
6
7
from Crypto.Cipher import AES
8
from Crypto.Util.Padding import pad
9
10
path = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
11
if sys.path[1] != path:
12
sys.path.insert(1, path)
13
14
from attacks.ecb import plaintext_recovery
15
from attacks.ecb import plaintext_recovery_harder
16
from attacks.ecb import plaintext_recovery_hardest
17
18
19
class TestECB(TestCase):
20
bytes = list(range(1, 256))
21
22
def _randbytes(self, k):
23
return bytes(choices(self.bytes, k=k))
24
25
def _encrypt(self, key, p):
26
return AES.new(key, AES.MODE_ECB).encrypt(p)
27
28
def test_plaintext_recovery(self):
29
key = self._randbytes(16)
30
for i in [0, 1, 2, 15, 16, 17, 31, 32]:
31
s = self._randbytes(i)
32
s_ = plaintext_recovery.attack(lambda p: self._encrypt(key, pad(p + s, 16)))
33
self.assertEqual(s, s_)
34
35
def test_plaintext_recovery_harder(self):
36
key = self._randbytes(16)
37
for i in range(16):
38
prefix = self._randbytes(i)
39
for j in [0, 1, 2, 15, 16, 17, 31, 32]:
40
s = self._randbytes(j)
41
s_ = plaintext_recovery_harder.attack(lambda p: self._encrypt(key, pad(prefix + p + s, 16)))
42
self.assertEqual(s, s_)
43
44
def test_plaintext_recovery_hardest(self):
45
key = self._randbytes(16)
46
for i in [0, 1, 2, 15, 16, 17, 31, 32]:
47
s = self._randbytes(i)
48
s_ = plaintext_recovery_hardest.attack(lambda p: self._encrypt(key, pad(self._randbytes(randrange(0, 16)) + p + s, 16)))
49
self.assertEqual(s, s_)
50
51