Obfuscated Android APK to Image

April 1, 2023

The following is a method to convert android apk dex files into images for image classification and malware assessment.

from PIL import Image
import os

directory = "Dexes\\Benign"

// Set the desired size of the output image
size = 128

for filename in os.listdir(directory):
    # Define the path to the text file
    text_file_path = os.path.join(directory, filename)

    // Read the contents of the text file as a string
    with open(text_file_path) as f:
        try:
            text_data = f.read()
        except:
            print('Failed to read')
            
    // Replace any null characters with a different character or sequence
    // text_data = text_data.replace("\0", "<null>")

    // Convert the text to bytes
    bytes_data = text_data

    // Calculate the number of pixels required to represent the data
    num_pixels = len(bytes_data)

    // Calculate the side length of the output image
    side_length = int(num_pixels ** 0.5) + 1

    // Calculate the number of padding zeros required to make the output image a square
    num_padding_zeros = side_length ** 2 - num_pixels

    // Pad the end of the input data with zeros
    bytes_data += b'\0' * num_padding_zeros

    // Create a PIL image from the bytes
    img = Image.frombytes("L", (side_length, side_length), bytes_data)

    // Resize the image to the desired size
    img = img.resize((size, size), Image.LANCZOS)

    // Define the path to save the image
    image_path = os.path.join("DexImages", "Benign", filename[:-4] + ".png")

    // Save the image
    img.save(image_path)