Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/rc4/fms.py
2587 views
1
from collections import Counter
2
3
4
def _possible_key_bit(key, c):
5
s = [i for i in range(256)]
6
j = 0
7
for i in range(len(key)):
8
j = (j + s[i] + key[i]) % 256
9
tmp = s[i]
10
s[i] = s[j]
11
s[j] = tmp
12
13
return (c[0] - j - s[len(key)]) % 256
14
15
16
def attack(encrypt_oracle, key_len):
17
"""
18
Recovers the hidden part of an RC4 key using the Fluhrer-Mantin-Shamir attack.
19
:param encrypt_oracle: the padding oracle, returns the encryption of a plaintext under a hidden key concatenated with the iv
20
:param key_len: the length of the hidden part of the key
21
:return: the hidden part of the key
22
"""
23
key = bytearray([3, 255, 0])
24
for a in range(key_len):
25
key[0] = a + 3
26
possible = Counter()
27
for x in range(256):
28
key[2] = x
29
c = encrypt_oracle(key[:3], b"\x00")
30
possible[_possible_key_bit(key, c)] += 1
31
key.append(possible.most_common(1)[0][0])
32
33
return key[3:]
34
35