
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.
- For every pixel, there is a Red, Green, and Blue value
- Each one of these is 8 bits.
- For example
- FF00000 = RED
- 00FF00 = GREEN
- 0000FF = BLUE
We can encode hidden data by setting the first bit in each pixel to a bit that exists in our ASCII message.
- For Example, the beginning of our hidden message starts with the bits 0, 1, and 0.
- We can set the first pixel in the image to be:
- RED Value: 0000 0000 (0x00)
- GREEN: 1000 0000 (0x80)
- Blue: 0000 0000 (0x00)
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")
