import pefile
import os
import sys
import random

def foolImphashChecksum(buf):
    path = os.path.join(os.environ['windir'], f'system32\\{imphashFoolModule}')

    if not os.path.isfile(path):
        info(f'[!] DLL specified in "{imphashFoolModule}" does not exist at path: {path}!')
        sys.exit(1)

    mod = pefile.PE(path, fast_load = True)
    mod.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"]])

    exports = [(e.ordinal, e.name) for e in mod.DIRECTORY_ENTRY_EXPORT.symbols]
    random.shuffle(exports)

    newbuf = buf

    for export in exports:
        exportName = export[1]
        if exportName == None or len(exportName) == 0: 
            continue

        if len(exportName) < len(imphashFoolAPIName):
            newbuf = replaceValue(newbuf, imphashFoolAPIName.encode(), exportName)
            print(f'\nReplaced imported {imphashFoolModule}!{imphashFoolAPIName} to {imphashFoolModule}!{exportName.decode()}')
            break

    mod.close()
    return newbuf

def replaceValue(buf, old, new):
    if len(old) > len(new):
        new += b'\x00' * (len(old) - len(new))
    elif len(new) > len(old):
        #raise Exception(f'New value for replacing ({new[:20]}) is longer than the value to be replaced({old[:20]}): ({len(new)} > {len(old)})')
        new = new[:len(old)]

    return buf.replace(old, new)
