Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/rsa/related_message.py
2589 views
1
import logging
2
import os
3
import sys
4
from itertools import product
5
6
from sage.all import Zmod
7
8
path = os.path.dirname(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 shared.polynomial import fast_polynomial_gcd
13
14
15
def attack(N, e, c1, c2, f1, f2):
16
"""
17
Recovers the shared secret if p1 and p2 are affinely related and encrypted with the same modulus and exponent.
18
Uses a fast GCD algorithm from "Polynomial Division and Greatest Common Divisors"
19
:param N: the modulus
20
:param e: the public exponent
21
:param c1: the ciphertext of the first encryption
22
:param c2: the ciphertext of the second encryption
23
:param f1: the first function to apply to the shared secret
24
:param f2: the second function to apply to the shared secret
25
:return: the shared secret
26
"""
27
x = Zmod(N)["x"].gen()
28
g1 = f1(x) ** e - c1
29
g2 = f2(x) ** e - c2
30
g = -fast_polynomial_gcd(g1, g2).monic()
31
return int(g[0])
32
33
34
def attack_xor(N, e, c1, c2, x):
35
"""
36
Recovers the shared secret if p1 = p2 ^ x and encrypted with the same modulus and exponent.
37
The complexity of this attack is 2^l, with l the hamming weight of x.
38
:param N: the modulus
39
:param e: the public exponent
40
:param c1: the ciphertext of the first encryption
41
:param c2: the ciphertext of the second encryption
42
:param x: the XOR difference
43
:return: a generator generating possible values of the shared secret
44
"""
45
shifts = []
46
for i in range(x.bit_length()):
47
if (x >> i) & 1 == 1:
48
shifts.append(1 << i)
49
50
logging.info(f"Brute forcing 2^{len(shifts)} possibilities, this might take some time...")
51
for signs in product([-1, 1], repeat=len(shifts)):
52
difference = sum(sign * shift for sign, shift in zip(signs, shifts))
53
yield attack(N, e, c1, c2, lambda x: x, lambda x: x + difference)
54
55