Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Attack-LSBit-Oracle/lsbitoracle.py
1402 views
1
from Crypto.Util.number import long_to_bytes, bytes_to_long
2
from Crypto.PublicKey import RSA
3
4
5
def lsbitoracle(flag_enc, _decrypt, e, N, upper_limit, lower_limit):
6
"""
7
Reference: https://crypto.stackexchange.com/questions/11053/rsa-least-significant-bit-oracle-attack
8
9
Function implementing LSBit Oracle Attack
10
11
*Warning*: Function does not return the last byte of the final plaintext
12
13
:parameters:
14
flag_enc : str
15
Ciphertext you want to decrypt
16
_decrypt : function
17
Function interacting with the server for decryption
18
e : int/long
19
Public Key exponent
20
N : long
21
Public Key Modulus
22
upper_limit: long
23
Maximum value of corresponding plaintext of flag_enc
24
lower_limit: long
25
Minimum value of corresponding plaintext of flag_enc
26
27
Since the attack messes up with the last byte of the plaintext, lsbitoracle
28
function returns only flag[:-1]. It returns -1 in case of any Exception
29
"""
30
flag = ""
31
i = 1
32
while lower_limit < upper_limit:
33
chosen_ct = long_to_bytes((bytes_to_long(flag_enc)*pow(2**i, e, N)) % N)
34
output = _decrypt(chosen_ct)
35
if ord(output[-1]) == 0:
36
upper_limit = (upper_limit + lower_limit)/2
37
elif ord(output[-1]) == 1:
38
lower_limit = (lower_limit + upper_limit)/2
39
else:
40
return -1
41
i += 1
42
# clearing the last byte from the flag
43
flag = lower_limit & (~0xff)
44
return long_to_bytes(flag)
45
46