image.png

Before working through this lab, you should take a look at the Hidden Message challenge.

This time, the message is hidden in the most significant bit of each pixel within the message.

We can encode hidden data by setting the first bit in each pixel to a bit that exists in our ASCII message.

We can reconstruct the original message by extracting the first bit from each pixel this time.

Here is the code to get that done:

from PIL import Image

def binary_to_str(binary_data):
    # Convert the binary string to characters, only keep ASCII (0-127)
    chars = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    return ''.join([chr(int(b, 2)) for b in chars if 0 <= int(b, 2) < 128])

def extract_flag_msb(image_path):
    # Open the image
    image = Image.open(image_path)
    pixels = list(image.getdata())
    
    # Extract the binary data using MSB
    binary_flag = ''
    for pixel in pixels:
        for color in pixel[:3]:  # Only read from R, G, B channels
            binary_flag += str((color >> 7) & 1)  # Get the MSB of each color channel
    
    # Uncomment to use end marker
    # end_marker = binary_flag.find('00000000')
    # if end_marker != -1:
    #     binary_flag = binary_flag[:end_marker]
    
    # Convert binary to text, filtering for ASCII characters
    flag = binary_to_str(binary_flag)
    print(f"Extracted flag: {flag}")

# Example usage
extract_flag_msb("pic1.png")

image.png