Skip to content

Instantly share code, notes, and snippets.

@idealwebsolutions
Last active July 28, 2021 00:12
Show Gist options
  • Save idealwebsolutions/9c513527d06297a969fb9ef0c2e6f155 to your computer and use it in GitHub Desktop.
Save idealwebsolutions/9c513527d06297a969fb9ef0c2e6f155 to your computer and use it in GitHub Desktop.
basic stego lsb to hide a plaintext message in a png image using a null term to determine end
#!/usr/bin/python3
from PIL import Image
NULL = 00000000
def string_bin(text):
return ''.join(['{:08b}'.format(ord(c)) for c in text])
def spl_bin(binary):
return [binary[i:i+8] for i in range(0, len(binary), 8)]
def bin_string(binary):
return ''.join(chr(eval('0b'+v)) for v in spl_bin(binary))
# In bytes
def get_max_message_size(image_file):
size = 0
with Image.open(image_file) as im:
w, h = im.size
size = w * h * 3/8
return round(size)
def hide_message_lsb(image_file, message):
i = 0
data = string_bin(message) + str(NULL)
with Image.open(image_file) as im:
w, h = im.size
for x in range(0, w):
for y in range(0, h):
pixel = list(im.getpixel((x, y)))
for n in range(0, 3):
if i < len(data):
pixel[n] = pixel[n] & ~1 | int(data[i])
i += 1
im.putpixel((x, y), tuple(pixel))
im.save('_{}'.format(image_file), 'PNG')
def extract_message(image_file):
ext = []
with Image.open(image_file) as im:
w, h = im.size
for x in range(0, w):
for y in range(0, h):
pixel = list(im.getpixel((x, y)))
for n in range(0, 3):
ext.append(str(pixel[n]&1))
bin_mesg = ''.join([str(x) for x in ext])
recv = []
for b in spl_bin(bin_mesg):
if b == str(11111111):
break
recv.append(b)
return ''.join(recv[:-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment