
This time the message is encoded using Least Significant Bit (LSB) encoding.
- For every pixel in the image, (Each pixel is 8 bits), the very last bit is set to a bit that makes up the secret message.
- By pulling the last bit from every pixel and recombining them, we get back an ASCII message this time.
I won’t explain how this program works here, but the process that is taking place here is excellent research material. (LSB encoding is super common!)
- Note: Some programs and websites will solve for LSB-encoded messages as well. It’s widespread.
- This program is an excellent one to save for future use as well!
from PIL import Image
def binary_to_str(binary_data):
# Convert the binary string to characters
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])
def extract_flag(image_path):
# Open the image
image = Image.open(image_path)
pixels = list(image.getdata())
# Extract the binary data
binary_flag = ''
for pixel in pixels:
for color in pixel[:3]: # Only read from R, G, B channels
binary_flag += str(color & 1)
# Find the stopping point and convert to string
end_marker = binary_flag.find('00000000')
if end_marker != -1:
binary_flag = binary_flag[:end_marker]
# Convert binary to text
flag = binary_to_str(binary_flag)
print(f"Extracted flag: {flag}")
# Example usage
extract_flag("pic_with_flag.png")
