Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/rsa/manger.py
2589 views
1
import logging
2
import os
3
import sys
4
5
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))
6
if sys.path[1] != path:
7
sys.path.insert(1, path)
8
9
from shared import ceil_div
10
from shared import floor_div
11
12
13
# Step 1.
14
def _step_1(padding_oracle, n, e, c):
15
f1 = 2
16
while padding_oracle((pow(f1, e, n) * c) % n):
17
f1 *= 2
18
19
return f1
20
21
22
# Step 2.
23
def _step_2(padding_oracle, n, e, c, B, f1):
24
f2 = floor_div(n + B, B) * f1 // 2
25
while not padding_oracle((pow(f2, e, n) * c) % n):
26
f2 += f1 // 2
27
28
return f2
29
30
31
# Step 3.
32
def _step_3(padding_oracle, n, e, c, B, f2):
33
mmin = ceil_div(n, f2)
34
mmax = floor_div(n + B, f2)
35
while mmin < mmax:
36
f = floor_div(2 * B, mmax - mmin)
37
i = floor_div(f * mmin, n)
38
f3 = ceil_div(i * n, mmin)
39
if padding_oracle((pow(f3, e, n) * c) % n):
40
mmax = floor_div(i * n + B, f3)
41
else:
42
mmin = ceil_div(i * n + B, f3)
43
return mmin
44
45
46
def attack(padding_oracle, n, e, c):
47
"""
48
Recovers the plaintext using Manger's attack.
49
More information: Manger J., "A Chosen Ciphertext Attack on RSA Optimal Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1 v2.0"
50
:param padding_oracle: the padding oracle taking integers, returns True if the PKCS #1 OAEP padding length is correct, False otherwise
51
:param n: the modulus
52
:param e: the public exponent
53
:param c: the ciphertext (integer)
54
:return: the plaintext (integer)
55
"""
56
k = ceil_div(n.bit_length(), 8)
57
B = 2 ** (8 * (k - 1))
58
# TODO: extend at some point?
59
assert 2 * B < n
60
logging.info("Executing step 1...")
61
f1 = _step_1(padding_oracle, n, e, c)
62
logging.info("Executing step 2...")
63
f2 = _step_2(padding_oracle, n, e, c, B, f1)
64
logging.info("Executing step 3...")
65
m = _step_3(padding_oracle, n, e, c, B, f2)
66
return m
67
68