import re

def extractAzorultZipBytes(rawbody, keyBytes):
    #keyBytes = bytes([0x0D, 0x0A, 0xC8])
    plainBytes = XOR2(rawbody, keyBytes, 1024 * 512)
    zipBytes = extractFile(plainBytes)
    return zipBytes

def XOR2(cipherBytes, keyBtes, maxsize):
    plainByteArray = []

    for i in range(0, len(cipherBytes)):
        if i  < maxsize:
            plainByte = cipherBytes[i] ^ keyBtes[i % len(keyBtes)]
        else:
            plainByte = cipherBytes[i]
        #plainByte = cipherBytes[i] ^ keyBtes[i % len(keyBtes)]
        plainByteArray.append(plainByte)

    plaintext = bytes(plainByteArray)
    #plaintext = plaintext.decode("utf-8")
    return plaintext

def extractFile(inp):
    pStart = re.compile(b'<file.*>',  re.MULTILINE)
    mStart = pStart.search(inp, re.MULTILINE)

    if mStart:
        startOfFile = mStart.span()[1]  # span returns a index tuple (begin of match, end of match)
        # print(mStart.group())
    else:
        return ""

    pEnd = re.compile(b'</file.*>',  re.MULTILINE)
    mEnd = pEnd.search(inp, re.MULTILINE)

    if mEnd:
        endOfFile = mEnd.span()[0]
        # print(mEnd.group())
        file = inp[startOfFile:endOfFile]
    else:
        file = ""

    #fw = open("/home/user/SampleLogsTesting/gar.zip", "wb")
    #fw.write(file)
    #fw.close()

    return file
