(Python) API Obfuscation by Unprotect

Created the Tuesday 06 December 2022. Updated 1 month, 3 weeks ago.


In this code, the hash function is used to obfuscate the names of the APIs that are imported from the kernel32.dll library. The hashed names are then used to call the APIs using the GetProcAddress and LoadLibrary functions. When the code is disassembled, the actual names of the APIs will be hidden and replaced with the hashed values.


            import ctypes

# Hash function to obfuscate the API names
def hash(str):
    hash = 5381
    for c in str:
        hash = (hash * 33 + ord(c)) % 2**32
    return hash

# Load the kernel32.dll library
hKernel32 = ctypes.windll.kernel32

# Use the hash function to obfuscate the names of the APIs
# we want to call from the library
lpLoadLibraryA = hKernel32.GetProcAddress(hKernel32, hash("LoadLibraryA"))
lpMessageBoxA = hKernel32.GetProcAddress(hKernel32, hash("MessageBoxA"))

# Call the APIs using the hashed names
hUser32 = ctypes.CFUNCTYPE(ctypes.c_void_p)(lpLoadLibraryA)("user32.dll")
ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint)(lpMessageBoxA)(None, "Hello World!", "API Hashing", 0)

# Clean up