Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_gcm.py
2587 views
1
import os
2
import sys
3
from random import randbytes
4
from unittest import TestCase
5
6
from Crypto.Cipher import AES
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.gcm import forbidden_attack
13
14
15
class TestGCM(TestCase):
16
def test_forbidden_attack(self):
17
# Test full GCM
18
key = randbytes(16)
19
iv = randbytes(16)
20
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
21
a1 = randbytes(16)
22
p1 = randbytes(16)
23
aes.update(a1)
24
c1, t1 = aes.encrypt_and_digest(p1)
25
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
26
a2 = randbytes(16)
27
p2 = randbytes(16)
28
aes.update(a2)
29
c2, t2 = aes.encrypt_and_digest(p2)
30
for h in forbidden_attack.recover_possible_auth_keys(a1, c1, t1, a2, c2, t2):
31
target_a = randbytes(16)
32
target_c = randbytes(16)
33
forged_t = forbidden_attack.forge_tag(h, a1, c1, t1, target_a, target_c)
34
try:
35
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
36
aes.update(target_a)
37
aes.decrypt_and_verify(target_c, forged_t)
38
break
39
except ValueError:
40
# Authentication failed, so we try the next authentication key.
41
continue
42
else:
43
self.fail()
44
45
# Test MAC only (sometimes known as GMAC)
46
key = randbytes(16)
47
iv = randbytes(16)
48
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
49
a1 = randbytes(16)
50
aes.update(a1)
51
t1 = aes.digest()
52
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
53
a2 = randbytes(16)
54
aes.update(a2)
55
t2 = aes.digest()
56
for h in forbidden_attack.recover_possible_auth_keys(a1, [], t1, a2, [], t2):
57
target_a = randbytes(16)
58
target_c = []
59
forged_t = forbidden_attack.forge_tag(h, a1, [], t1, target_a, target_c)
60
try:
61
aes = AES.new(key, AES.MODE_GCM, nonce=iv)
62
aes.update(target_a)
63
aes.verify(forged_t)
64
break
65
except ValueError:
66
# Authentication failed, so we try the next authentication key.
67
continue
68
else:
69
self.fail()
70
71