Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Attack-LSBit-Oracle-variant/lsbitoracle-variant.py
1402 views
1
from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse
2
3
def lsbitoracle_variant(flag_enc, _decrypt, e, N, len_flag):
4
"""
5
Function implementing a variant of LSBit Oracle Attack
6
Time complexity is O(len_flag) where len_flag is the length of the flag in bits
7
8
:parameters:
9
flag_enc : str
10
Ciphertext we want to decrypt
11
_decrypt : function
12
Function interacting with the remote service for decryption
13
e : int/long
14
Public Key exponent
15
N : long
16
Public Key modulus
17
len_flag : int
18
Length of plaintext in bits (for eg. 128 bit long flag)
19
20
Function returns -1 in case of any Exception, with appropriate error message
21
"""
22
output = _decrypt(flag_enc)
23
assert output == "\x01" or output == "\x00"
24
flag = bin(ord(output))[2:]
25
26
for i in range(1, len_flag):
27
temp_cal = 2**i
28
try:
29
assert GCD(temp_cal, N) == 1
30
except:
31
print "[-] GCD(2**i, N) != 1, obtained one factor of N successfully"
32
return -1
33
inv = inverse(temp_cal, N)
34
chosen_ct = long_to_bytes((bytes_to_long(flag_enc)*pow(inv, e, N)) % N)
35
output = _decrypt(chosen_ct)
36
try:
37
assert output == "\x01" or output == "\x00"
38
except:
39
print "[-] Unusual output obtained. Exiting..."
40
return -1
41
# Compute i-th bit of plaintext based on the output obtained above
42
flag_char = (ord(output) - (int(flag, 2)*inv) % N) % 2
43
# Prepend i-th bit calculated to the plaintext string
44
flag = str(flag_char) + flag
45
if len(flag) % 8 == 0:
46
print "Plaintext recovered till now: ", long_to_bytes(int(flag, 2))
47
return long_to_bytes(int(flag, 2))
48
49