Path: blob/master/RSA-encryption/Attack-LSBit-Oracle-variant/lsbitoracle-variant.py
1402 views
from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse12def lsbitoracle_variant(flag_enc, _decrypt, e, N, len_flag):3"""4Function implementing a variant of LSBit Oracle Attack5Time complexity is O(len_flag) where len_flag is the length of the flag in bits67:parameters:8flag_enc : str9Ciphertext we want to decrypt10_decrypt : function11Function interacting with the remote service for decryption12e : int/long13Public Key exponent14N : long15Public Key modulus16len_flag : int17Length of plaintext in bits (for eg. 128 bit long flag)1819Function returns -1 in case of any Exception, with appropriate error message20"""21output = _decrypt(flag_enc)22assert output == "\x01" or output == "\x00"23flag = bin(ord(output))[2:]2425for i in range(1, len_flag):26temp_cal = 2**i27try:28assert GCD(temp_cal, N) == 129except:30print "[-] GCD(2**i, N) != 1, obtained one factor of N successfully"31return -132inv = inverse(temp_cal, N)33chosen_ct = long_to_bytes((bytes_to_long(flag_enc)*pow(inv, e, N)) % N)34output = _decrypt(chosen_ct)35try:36assert output == "\x01" or output == "\x00"37except:38print "[-] Unusual output obtained. Exiting..."39return -140# Compute i-th bit of plaintext based on the output obtained above41flag_char = (ord(output) - (int(flag, 2)*inv) % N) % 242# Prepend i-th bit calculated to the plaintext string43flag = str(flag_char) + flag44if len(flag) % 8 == 0:45print "Plaintext recovered till now: ", long_to_bytes(int(flag, 2))46return long_to_bytes(int(flag, 2))474849