0

I am trying to find remaining part of the key by brute-forcing the remaining 4 characters. Then we decrypt using each key and check if the decrypted message has "Salam" at the starting.

CODE:

from Cryptodome.Cipher import AES
def revpad(s):
        """
        This function is to remove padding.

        parameters:
                s:str
                                string to be reverse padded

        """

        k=ord(s[-1])
        temp=0                                          #temporary variable to check padding
        for i in range (1,k):                           #for loop to check padding
                if(s[-i]!=s[-1]):                       #comparision of bytes with the last Byte
                        temp=1

        if(temp==0):
                return (s[:-k])                         #Reverse padded string
        else:
                return ("Wrong padding")



def decrypt(ct,key):
        """
        This function is for decrypting ciphertext in ECB mode

        parameters:
                ct: str
                                ciphertext to be decrypted
                key: str
                                key for ECB mode encryption whose lenght is always a multiple of 16 in this case
        """

        plaintxt=AES.new(key,AES.MODE_ECB)
        pt=plaintxt.decrypt(ct)

        return revpad(pt)                                  #After decrypting padding should be removed

if __name__ == "__main__":
    ciphertext = open("ciphertext2.dat" , "r", errors='ignore').read()
    partial_key = open("partial-key.dat" , "r")
    for i in range(256):
        for j in range(256):
            for k in range(256):
                for l in range(256):
                    remaining_key = chr(i)+chr(j)+chr(k)+chr(l)

                    key = partial_key + remaining_key
                    decrypted_text = decrypt(ciphertext , key)
                    if(decrypted_text[:5] == "Salam"):
                        print(decrypted_text)

and i am getting this error: ERROR:TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'str' can anyone guide me what i am doing wrong.

Abbas
  • 59
  • 7
  • 1
    You forgot to apply the `.read()` method to opened file object here: `partial_key = open("partial-key.dat" , "r")`. I suspect you meant to do `partial_key = open("partial-key.dat" , "r").read()` – President James K. Polk Nov 16 '20 at 21:40
  • 1
    [The `itertools.product()` method](https://docs.python.org/3/library/itertools.html#itertools.product) would make you code a lot cleaner. You could replace those quadruply-nested for loops with this one line: `for i, j, k, l in itertools.product(range(256), repeat = 4):` – President James K. Polk Nov 16 '20 at 21:45

0 Answers0