Path: blob/master/RSA-encryption/Attack-LSBit-Oracle/lsbitoracle.py
1402 views
from Crypto.Util.number import long_to_bytes, bytes_to_long1from Crypto.PublicKey import RSA234def lsbitoracle(flag_enc, _decrypt, e, N, upper_limit, lower_limit):5"""6Reference: https://crypto.stackexchange.com/questions/11053/rsa-least-significant-bit-oracle-attack78Function implementing LSBit Oracle Attack910*Warning*: Function does not return the last byte of the final plaintext1112:parameters:13flag_enc : str14Ciphertext you want to decrypt15_decrypt : function16Function interacting with the server for decryption17e : int/long18Public Key exponent19N : long20Public Key Modulus21upper_limit: long22Maximum value of corresponding plaintext of flag_enc23lower_limit: long24Minimum value of corresponding plaintext of flag_enc2526Since the attack messes up with the last byte of the plaintext, lsbitoracle27function returns only flag[:-1]. It returns -1 in case of any Exception28"""29flag = ""30i = 131while lower_limit < upper_limit:32chosen_ct = long_to_bytes((bytes_to_long(flag_enc)*pow(2**i, e, N)) % N)33output = _decrypt(chosen_ct)34if ord(output[-1]) == 0:35upper_limit = (upper_limit + lower_limit)/236elif ord(output[-1]) == 1:37lower_limit = (lower_limit + upper_limit)/238else:39return -140i += 141# clearing the last byte from the flag42flag = lower_limit & (~0xff)43return long_to_bytes(flag)444546