Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_ctr.py
2587 views
1
import os
2
import sys
3
from random import randbytes
4
from random import randint
5
from unittest import TestCase
6
7
from Crypto.Cipher import AES
8
from Crypto.Util import Counter
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.ctr import bit_flipping
15
from attacks.ctr import separator_oracle
16
17
18
class TestCTR(TestCase):
19
def _encrypt(self, key, p):
20
return AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(p)
21
22
def _decrypt(self, key, p):
23
return AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(p)
24
25
def _valid_separators(self, separator_byte, separator_count, key, c):
26
p = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(c)
27
return p.count(separator_byte) == separator_count
28
29
def test_bit_flipping(self):
30
key = randbytes(16)
31
p = randbytes(32)
32
p_ = randbytes(16)
33
c = self._encrypt(key, p)
34
35
c_ = bit_flipping.attack(c, 0, p[0:len(p_)], p_)
36
p__ = self._decrypt(key, c_)
37
self.assertEqual(p_, p__[0:len(p_)])
38
39
c_ = bit_flipping.attack(c, 16, p[16:16 + len(p_)], p_)
40
p__ = self._decrypt(key, c_)
41
self.assertEqual(p_, p__[16:16 + len(p_)])
42
43
def test_crime(self):
44
# TODO: CRIME attack is too inconsistent in unit tests.
45
pass
46
47
def test_separator_oracle(self):
48
separator_byte = ord("\x00")
49
separator_count = randint(1, 10)
50
key = randbytes(16)
51
# We have to replace separators by some other byte.
52
p = randbytes(16).replace(b"\x00", b"\x01")
53
for _ in range(separator_count):
54
# We have to replace separators by some other byte.
55
p += bytes([separator_byte]) + randbytes(16).replace(b"\x00", b"\x01")
56
57
c = self._encrypt(key, p)
58
59
p_ = separator_oracle.attack(lambda c: self._valid_separators(separator_byte, separator_count, key, c), separator_byte, c)
60
self.assertEqual(p, p_)
61
62