Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

P C52321 Pro X CS2321 PROJECT 5B STEGANOGRAPHY Your task for this project will b

ID: 3705477 • Letter: P

Question

P C52321 Pro X CS2321 PROJECT 5B STEGANOGRAPHY Your task for this project will be to create a program which can hide a mossage in a picture and thon extract the messago. This project will be worth 20 points. Please use proper formatting, comments and naming conventions The Wilipedia entry for stoganography provides the following: Steganography is the art and science of writing hidden messages in such a way that no one apart from the intended recipient knows of the existence of the message, this is in contrast to cryptography, where the existence of the message itself is not disguised, but the content is obacured Generally, a steganographic message will appear to be something else: a picture, an article, a shopping list, or some other message. This apparent message is the cover text. Por instance, a message may be hidden by using invisible ink between the visible lines of innocuous documents. The advantage of steganography over cryptography alone is that messages do not attract attention to themaelves, to messengers, or to recipients. An unhidden coded message, no matter how unbreakable it is, will arouse suspicion and may in itself be incriminating, as in countries where encryption is illegal Whon we use the RGB values (red, green, blue) there are over 16 million different colors. The human eye cannot always distinguish between all

Explanation / Answer

main.py

import base64, sys, os.path
sys.path.append('/usr/local/python3.5/site-packages')
import cv2 as cv
from LSBStegno import LSBStegno


#Hide text
def hide_text(text, in_image, out_image="res.png"):
    carrier = cv.imread(in_image)
    stegno = LSBStegno(carrier)
    if (os.path.isfile(text)):
        f = open(text,'r')
        text = f.read()

    stegno.hideText(text)
    stegno.saveImage(out_image)

#Unhide text
def unhide_text(in_image):
    im = cv.imread(in_image)
    stegno = LSBStegno(im)
    print(stegno.unhideText())

#Hide image
def hide_image(secret_img, carrier_img, out_image="res.png"):
    imagetohide = cv.LoadImage(secret_img)
    carrier = cv.LoadImage(carrier_img)
    stegno = LSBStegno(carrier)
    stegno.hideImage(imagetohide)
    stegno.saveImage(out_image)

#Unhide image
def unhide_image(in_image,out_image):
    inp = cv.LoadImage(in_image)
    stegno = LSBStegno(inp)
    dec = stegno.unhideImage()
    cv.SaveImage(out_image, dec) #Image retrieve into the other image


#Hide binary
def hide_binary(in_image, out_image):
    carrier = cv.LoadImage(in_image)
    stegno = LSBStegno(carrier)
    stegno.hideBin("ls") #I took the start binary I found
    stegno.saveImage(out_image)

#Unhide binary
def unhide_binary(in_image):
    inp = cv.LoadImage("res.png")
    stegno = LSBStegno(inp)
    bin = stegno.unhideBin()
    f = open("res","wb") #Write the binary back to a file
    f.write(bin)
    f.close()

def helper():
    example1 = """* to hide text * example: python3 main.py hide_text "hello world" original.png out.png"""
    example2 = """* to unhide text * example: python3 main.py unhide_text out.png"""
    example3 = """* other options * hide_image, unhide_image, hide_binary, unhide_binary"""
    print(" ||| WELCOME TO LSB STEG ||| %s %s %s ENJOY " % (example1,example2,example3))
    sys.exit()

if __name__=="__main__":
    if len(sys.argv) < 2:
        raise Exception("Arguments must be at least 1!")
    else:
        start = sys.argv[1]
        if start == "hide_text":
            hide_text(sys.argv[2],sys.argv[3],sys.argv[4])
        elif start == "unhide_text":
            unhide_text(sys.argv[2])
        elif start == "hide_image":
            hide_image(sys.argv[2],sys.argv[3],sys.argv[4])
        elif start == "unhide_image":
            unhide_image(sys.argv[2],sys.argv[3])
        elif start == "hide_binary":
            hide_binary(sys.argv[2],sys.argv[3])
        elif start == "unhide_binary":
            unhide_binary(sys.argv[2])
        elif start == "-h":
            helper()
        else:
            raise Exception(start+" was a not valid argument! run -h for help")

LSBStegno.py

#!/usr/local/bin/python3
# coding=UTF-8

try:
    import cv2.cv as cv
except:
    try:
        import cv2 as cv
    except:
        exit("try sudo pip3 install opencv-python first")
import sys

class SteganographyException(Exception):
    pass

class LSBSteg():
    def __init__(self, im):
        self.image = im
        heights,widths,channels = im.shape
        self.width = widths
        self.height = heights
        self.size = self.width * self.height
        self.nbchannels = channels

        self.mask1Values = [1,2,4,8,16,32,64,128]
        #Mask used to put one ex:1->00000001, 2->00000010 .. associated with OR bitwise
        self.mask1 = self.mask1Values.pop(0) #Will be used to do bitwise operations

        self.mask0Values = [254,253,251,247,239,223,191,127]
        #Mak used to put zero ex:254->11111110, 253->11111101 .. associated with AND bitwise
        self.mask0 = self.mask0Values.pop(0)

        self.curwidth = 0 #Current width position
        self.curheight = 0 #Current height position
        self.curchan = 0 #Current channel position

    def saveImage(self,filename):
    # Save the image using the given filename
        cv.imwrite(filename, self.image)


    def putBinaryValue(self, bits): #Put the bits in the image
        for c in bits:
            value = list(self.image[self.curheight,self.curwidth]) #Get the pixel valueue as a list
            if int(c) == 1:
                value[self.curchan] = int(value[self.curchan]) | self.mask1 #OR with mask1
            else:
                value[self.curchan] = int(value[self.curchan]) & self.mask0 #AND with mask0

            self.image[self.curheight,self.curwidth] = tuple(value)
            self.nextSpace() #Move "cursor" to the next space

    def nextSpace(self):#Move to the next slot were information can be taken or put
        if self.curchan == self.nbchannels-1: #Next Space is the following channel
            self.curchan = 0
            if self.curwidth == self.width-1: #Or the first channel of the next pixel of the same line
                self.curwidth = 0
                if self.curheight == self.height-1:#Or the first channel of the first pixel of the next line
                    self.curheight = 0
                    if self.mask1 == 128: #Mask 1000000, so the last mask
                        raise SteganographyException("Image filled")
                    else: #Or instead of using the first bit start using the second and so on..
                        self.mask1 = self.mask1Values.pop(0)
                        self.mask0 = self.mask0Values.pop(0)
                else:
                    self.curheight +=1
            else:
                self.curwidth +=1
        else:
            self.curchan +=1

    def readBit(self): #Read a single bit int the image
        value = self.image[self.curheight,self.curwidth][self.curchan]
        value = int(value) & self.mask1
        self.nextSpace()
        if value > 0:
            return "1"
        else:
            return "0"

    def readByte(self):
        return self.readBits(8)

    def readBits(self, nb): #Read the given number of bits
        bits = ""
        for i in range(nb):
            bits += self.readBit()
        return bits

    def byteValue(self, value):
        return self.binValue(value, 8)

    def binValue(self, value, bitsize): #Return the binary valueue of an int as a byte
        binvalue = bin(value)[2:]
        if len(binvalue) > bitsize:
            raise SteganographyException("binary valueue larger than the expected size")
        while len(binvalue) < bitsize:
            binvalue = "0"+binvalue
        return binvalue

    def hideText(self, txt):
        l = len(txt)
        binl = self.binValue(l, 16) #Length coded on 2 bytes so the text size can be up to 65536 bytes long
        self.putBinaryValue(binl) #Put text length coded on 4 bytes
        for char in txt: #And put all the chars
            c = ord(char)
            self.putBinaryValue(self.byteValue(c))

    def unhideText(self):
        ls = self.readBits(16) #Read the text size in bytes
        l = int(ls,2)
        i = 0
        unhideTxt = ""
        while i < l: #Read all bytes of the text
            temp = self.readByte() #So one byte
            i += 1
            unhideTxt += chr(int(temp,2)) #Every chars concatenated to str
        return unhideTxt

    def hideImage(self, imtohide):
        w = imtohide.width
        h = imtohide.height
        if self.width*self.height*self.nbchannels < w*h*imtohide.channels:
            raise SteganographyException("Carrier image not big enough to hold all the datas to steganography")
        binw = self.binValue(w, 16) #Width coded on to byte so width up to 65536
        binh = self.binValue(h, 16)
        self.putBinaryValue(binw) #Put width
        self.putBinaryValue(binh) #Put height
        for h in range(imtohide.height): #Iterate the hole image to put every pixel valueues
            for w in range(imtohide.width):
                for chan in range(imtohide.channels):
                    value = imtohide[h,w][chan]
                    self.putBinaryValue(self.byteValue(int(value)))


    def unhideImage(self):
        width = int(self.readBits(16),2) #Read 16bits and convert it in int
        height = int(self.readBits(16),2)
        unhideimg = cv.CreateImage((width,height), 8, 3) #Create an image in which we will put all the pixels read
        for h in range(height):
            for w in range(width):
                for chan in range(unhideimg.channels):
                    value = list(unhideimg[h,w])
                    value[chan] = int(self.readByte(),2) #Read the valueue
                    unhideimg[h,w] = tuple(value)
        return unhideimg

    def hideBin(self, filename):
        f = open(filename,'rb')
        bin = f.read()
        l = len(bin)
        if self.width*self.height*self.nbchannels < l+64:
            raise SteganographyException("Carrier image not big enough to hold all the datas to steganography")
        self.putBinaryValue(self.binValue(l, 64))
        for byte in bin:
            self.putBinaryValue(self.byteValue(ord(byte)))

    def unhideBin(self):
        l = int(self.readBits(64),2)
        output = ""
        for i in range(l):
            output += chr(int(self.readByte(),2))
        return output

if __name__=="__main__":
    pass