Search code examples
pythonencryptioncryptographyxor

Split encrypted string and xor it with a shorter string at every point


I'm new to Python, but have a decent amount of programming experience (although I don't really know how I would do this in another language either).

I have a long-ish encrypted hex string, and what I would like to do is xor that string with the at every position such that I am xor-ing an equal length string from the encrypted string at every point.

For example, if I had the string 12104c06134e5709 and the as 74484520 I would like to do:

  • 12104c06 xor 74484520
  • 2104c061 xor 74484520
  • 104c0613 xor 74484520

(etc...)

I'm not overly concerned how the result is stored at this point, I suppose an array would be fine (a list in Python, I think).

Is this possible? Thanks for all help.


Solution

  • def iterXOR(hexString, otherString):
    
        #Convert otherString to a hex (the 16 is for base 16)
        otherNum = int(otherString, 16)
    
        #Iterate over the hexString
        for i in range(0, len(hexString) - len(otherString) + 1):
    
            #Grab the substring of length N beginning at index i
            #Where N is the length of otherString and i is the index
            subString = hexString[i:i+len(otherString)]
    
            #Convert the substring to a hex number
            hexNum = int(subString, 16)
    
            #Print the product of the XOR (or do whatever you want here)
            print hex(hexNum ^ otherNum)
    
    
    #Usage
    iterXOR("12104c06134e5709", "74484520")
    

    Outputs:

    >>> 
    0x66580926
    0x554c8541
    0x64044333
    0x70882414
    0x384e566e
    0xb42971c5
    0x725b0b77
    0x157ca050
    0x67061229