I've built a Python Steganographer and am trying to add a GUI to it. After my previous question regarding reading all kinds of files in Python. Since, the steganographer can only encode bytes in image. I want to add support to directly encode a file of any extension and encoding in it. For this, I am reading the file in binary and trying to encode it. It works fine for files which basically contains plain-text UTF-8 because it can easily encode .txt
and .py
files.
My updated code is:
from PIL import Image
import os
class StringTooLongException(Exception):
pass
class InvalidBitValueException(Exception):
pass
def str2bin(message):
binary = bin(int.from_bytes(message, 'big'))
return binary[2:]
def bin2str(binary):
n = int(binary, 2)
return n.to_bytes((n.bit_length() + 7) // 8, 'big')
def hide(filename, message, bits=2):
image = Image.open(filename)
binary = str2bin(message) + '00000000'
if (len(binary)) % 8 != 0:
binary = '0'*(8 - ((len(binary)) % 8)) + binary
data = list(image.getdata())
newData = []
if len(data) * bits < len(binary):
raise StringTooLongException
if bits > 8:
raise InvalidBitValueException
index = 0
for pixel in data:
if index < len(binary):
pixel = list(pixel)
pixel[0] >>= bits
pixel[0] <<= bits
pixel[0] += int('0b' + binary[index:index+bits], 2)
pixel = tuple(pixel)
index += bits
newData.append(pixel)
image.putdata(newData)
image.save(os.path.dirname(filename) + '/coded-'+os.path.basename(filename), 'PNG')
return len(binary)
def unhide(filename, bits=2):
image = Image.open(filename)
data = image.getdata()
if bits > 8:
raise InvalidBitValueException
binary = ''
index = 0
while not (len(binary) % 8 == 0 and binary[-8:] == '00000000'):
value = '00000000' + bin(data[index][0])[2:]
binary += value[-bits:]
index += 1
message = bin2str(binary)
return message
Now, the problem comes when I try to hide .pdf
or .docx
files in it. Several things are happening:
1) Microsoft Word or Adobe Acrobat shows that the file is corrupt.
2)The file size is considerable reduced from 40KB to 3KB which is a clear sign of error.
I think that the reason behind this could be that the file contains a NULL character reading which my program does not read further. Do you have any alternative idea for it?
I have an idea to change the ending byte but it may still have the same result as a file may contain that byte.
Thanks, again!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…