Exemple #1
0
def main():
    '''
    Main function to handle the script

    @return : None
    '''
    args = handleArgs()
    cypher = Cypher(args.key,
                    args.size)  # create the Cypher obj from our Cypher class
    steganography = Steganography(
        args.imageInput, args.compression
    )  # create the Steganography obj from our Steganography class

    if args.decrypt:  # if decrypt option is used
        encoded = steganography.decode(
        )  # decode the message hidden into image
        result = cypher.decrypt(encoded)  # decrypt the message found

        # Write the decrypted message in the output file
        with open(args.dataOutput, 'wb') as writeFile:
            byteArray = bytearray(result)
            writeFile.write(byteArray)
    else:  # if encrypt option is used
        # Read bytes of input file
        with open(args.dataInput, 'rb') as readFile:
            data = [i for i in readFile.read()]
            encoded = cypher.encrypt(data)  # encrypt the message
            image = steganography.encode(
                encoded)  # encode the message into image
            '''
            Copy the encoded image to a new file in best quality
            to ensure that image's bits are not corrupted by compression
            '''
            image.save(args.imageOutput, quality=100)
Exemple #2
0
def decProcess(decfile,img,emkey,out_f,cframe,nframe):
	print('[INFO] LOADING MAGE')
	in_im = cv2.imread(img)
	print('[INFO] IMAGE LOADED SUCCESSFULLY.')
	stegano = Steganography(in_im,emkey)
	print('[INFO] GETTING RECIEVER\'S UID.')
	ruid = stegano.extract_receiver()
	print('[INFO] RECIEVER\'S UID : {}.'.format(ruid))
	print('[INFO] INITIATING FACICAL RECOGNITION PROCESS.')
	
	if(auth(ruid)):
		print('[INFO] RECIEVER AUTHORIZED.')
		print('[INFO] EXTRACTING KEY FROM IMAGE.')
		byte_lst = stegano.decode_data()
		key = bytes(byte_lst)
		print('[INFO] KEY EXTRACTED SUCCESSFULLY.')
		print('[INFO] INITIATING DECRYPTION PROCESS.')
		dec = Decryption(decfile)
		try:
			dec.decrypt_data(key,out_f)
		except:
			print('[INFO] USER NOT AUTHORIZED. CHECK KEY.')
			tkinter.messagebox.showinfo("ERROR", "KEY ERROR. PLEASE CHECK IMAGE OR EMBEDDING KEY.")
		else:
			print('[INFO] DECRYPTION COMPLETED SUCCESSFULLY.')
			tkinter.messagebox.showinfo("Success", "DECRYPTED FILE SAVED.")
		
	else:
		print('[INFO] IDENTITY OF RECIEVER NOT VERIFIED.')
		tkinter.messagebox.showinfo("ERROR", "RECIEVER NOT AUTHORIZED.")
		
	showPrev(cframe,nframe)
Exemple #3
0
def audio_encrypt(filename, msg):
    output_filename = ""
    if filename != "":
        if not filename.endswith(".wav"):
            print("Invalid image file format! Encryption only accepts .wav audio file")
            return False
        filename = validate_file(filename)
        if filename == -1:
            return False
    else:
        files = listdir(getcwd())
        for i in files:
            if i.endswith(".wav"):
                filename = i
                print filename
                break
        flag = 0
        if filename != "":
            print("Found some audio files in the current directory")
            ch = raw_input("Do you want me to encrypt on "+filename+"?(Y/N)? ").upper()
            if ch == 'Y':
                flag = 1
        if flag == 0:
            ch = raw_input("Would you like to enter a filename?(Y/N)? ").upper()
            if ch == 'Y':
                filename = raw_input("Enter the filename: ")
                filename = validate_file(filename)
                if filename == "-1":
                    return False
            else:
                ch = raw_input("Would you like me to encrypt it on any random file?(Y/N)").upper()
                if ch == 'Y':
                    files = listdir(FILE_PATH+"Audio")
                    output_filename = choice(files)
                    filename = FILE_PATH+"Audio\\"+output_filename
                    output_filename = output_filename[:-4]+"_encrypted.wav"
                else:
                    return False
    aud = Steganography.open(filename, "rb")
    if msg == "":
        msg = raw_input("Enter a message to be hidden: ")
    new_data = Steganography.audio_encryption(aud, msg)
    x = 1
    if output_filename == "":
        output_filename = filename[:-4] + "_encrypted.wav"
    while isfile(output_filename):
        output_filename = output_filename[:-4] + str(x) + ".wav"
        x += 1
    new_aud = Steganography.open(output_filename, "wb")
    new_aud = Steganography.set_params(new_aud, aud)
    new_aud.writeframes(new_data)
    new_aud.close()
    print("Encryption Done")
    print("File is saved as: "+output_filename)
    startfile(output_filename)
    return True
    def test_badSavingGrayImageToText(self):
        """
        Test that trying to save a gray-scale image as a text produces an exception.
        """
        sourcePath = 'files/bridge_dog_h' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToTextFile, self.targetImageFilePath)
    def test_badSavingTextToGrayImage(self):
        """
        Test that trying to save a text file as an image produces an exception.
        """
        sourcePath = 'files/mona_small_h' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToImage, self.targetTextFilePath)
    def test_embedHorizontalExtractVertical(self):
        """
        Test that trying to extract a horizontal message using a vertical scan, produces an exception.
        """
        sourcePath = 'files/lena_full_h' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()

        self.assertEqual(message, None)
    def test_embedVerticalExtractHorizontal(self):
        """
        Test that trying to extract a vertical message using a horizontal scan, produces an exception.
        """
        sourcePath = 'files/mona_small_v' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertEqual(message, None)
Exemple #8
0
    def test_embedHorizontalExtractVertical(self):
        """
        Test that trying to extract a horizontal message using a vertical scan, produces an exception.
        """
        sourcePath = 'files/lena_full_h' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()

        self.assertEqual(message, None)
Exemple #9
0
    def test_embedVerticalExtractHorizontal(self):
        """
        Test that trying to extract a vertical message using a horizontal scan, produces an exception.
        """
        sourcePath = 'files/mona_small_v' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertEqual(message, None)
    def test_badSavingColorImageToText(self):
        """
        Test that trying to save a color image as a text produces an exception.
        """
        sourcePath = 'files/nature_sunflower_v' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToTextFile, self.targetImageFilePath)
Exemple #11
0
def encrypt(filename,  msg):
    output_filename = ""
    if filename != "":
        if not filename.endswith(".png"):
            print("Invalid image file format! Encryption only accepts .png file")
            return False
        filename = validate_file(filename)
        if filename == -1:
            return False
    else:
        files = listdir(getcwd())
        for i in files:
            if i.endswith(".png"):
                filename = i
                print filename
                break
        flag = 0
        if filename != "":
            print("Found some image files in the current directory")
            ch = raw_input("Do you want me to encrypt on "+filename+"?(Y/N)? ").upper()
            if ch == 'Y':
                flag = 1
        if flag == 0:
            ch = raw_input("Would you like to enter a filename?(Y/N)? ").upper()
            if ch == 'Y':
                filename = raw_input("Enter the filename: ")
                filename = validate_file(filename)
                if filename == "-1":
                    return False
            else:
                ch = raw_input("Would you like me to encrypt it on any random file?(Y/N)").upper()
                if ch == 'Y':
                    files = listdir(FILE_PATH+"Image")
                    output_filename = choice(files)
                    filename = FILE_PATH+"Image\\"+output_filename
                    output_filename = output_filename[:-4]+"_encrypted.png"
                else:
                    return False
    img = Steganography.imread(filename)
    if msg == "":
        msg = raw_input("Enter a message to be hidden: ")

    new_img = Steganography.image_encryption(img, msg)
    x = 1
    if output_filename == "":
        output_filename = filename[:-4] + "_encrypted.png"
    while isfile(output_filename):
        output_filename = output_filename[:-4] + str(x) + ".png"
        x += 1
    Steganography.imwrite(output_filename, new_img)
    print("Encryption Done")
    print("File is saved as: "+output_filename)
    startfile(output_filename)
    return True
Exemple #12
0
    def test_badSavingGrayImageToText(self):
        """
        Test that trying to save a gray-scale image as a text produces an exception.
        """
        sourcePath = 'files/bridge_dog_h' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToTextFile,
                          self.targetImageFilePath)
Exemple #13
0
    def test_badSavingColorImageToText(self):
        """
        Test that trying to save a color image as a text produces an exception.
        """
        sourcePath = 'files/nature_sunflower_v' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToTextFile,
                          self.targetImageFilePath)
Exemple #14
0
    def test_badSavingTextToGrayImage(self):
        """
        Test that trying to save a text file as an image produces an exception.
        """
        sourcePath = 'files/mona_small_h' + self.ext

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()

        self.assertRaises(TypeError, message.saveToImage,
                          self.targetTextFilePath)
Exemple #15
0
def encode_stegano(sc_data,uid):
	os.system('clear')
	print('Starting Steganography Encoding Process')
	in_f = input('Source image (should be .png format)\t: ')
	key = input('Steganography Encoding key (Caution: sensitive information)\t: ')
	in_im = cv2.imread(in_f)
	stegano = Steganography(in_im,key)
	res_img = stegano.encode_data(sc_data,uid)
	print('AES Encryption key successfully embedded into the image.')
	out_f = input('Encoded image (should be .png format)\t: ')
	cv2.imwrite(out_f,res_img)
	print('Updated image saved.')
	ip = input('Press any key to continue...')
Exemple #16
0
def decrypt(filename):
    if not filename.endswith(".png"):
        print("Invalid input filename")
        return False
    filename = validate_file(filename)
    if filename == -1:
        return False
    try:
        img = Steganography.imread(filename)
        msg = Steganography.image_decryption(img)
        print "Message is: ", msg
    except Exception as e:
        print str(e)
    return True
Exemple #17
0
def audio_decrypt(filename):
    if not filename.endswith(".wav"):
        print("Invalid input filename")
        return False
    filename = validate_file(filename)
    if filename == -1:
        return False
    try:
        aud = Steganography.open(filename, "rb")
        msg = Steganography.audio_decryption(aud)
        print "Message is: ", msg
    except Exception as e:
        print str(e)
    return True
    def test_extractGrayImageVertical(self):
        """
        Test the extraction of a gray-scale in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/bridge_dog_v' + self.ext
        expectedPath = 'files/dog' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_extractLongTextVertical(self):
        """
        Test the extraction of a long text file in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/lena_full_v' + self.ext
        expectedPath = 'files/full.txt'

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
    def test_extractShortTextHorizontal(self):
        """
        Test the extraction of a short text file in a medium, using a horizontal raster scan.
        """
        sourcePath = 'files/mona_small_h' + self.ext
        expectedPath = 'files/small.txt'

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
    def test_extractColorImageVertical(self):
        """
        Test the extraction of a color in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/nature_sunflower_v' + self.ext
        expectedPath = 'files/sunflower' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_embedLongTextVertical(self):
        """
        Test the embedding of a long text file in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/full.txt'
        expectedPath = 'files/lena_full_v' + self.ext
        mediumPath = 'files/lena' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_embedShortTextHorizontal(self):
        """
        Test the embedding of a short text file in a medium, using a horizontal raster scan.
        """
        sourcePath = 'files/small.txt'
        expectedPath = 'files/mona_small_h' + self.ext
        mediumPath = 'files/mona' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_embedColorImageVertical(self):
        """
        Test the embedding of a color image in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/sunflower' + self.ext
        expectedPath = 'files/nature_sunflower_v' + self.ext
        mediumPath = 'files/nature' + self.ext

        message = Message(filePath=sourcePath, messageType='ColorImage')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #25
0
    def test_extractShortTextHorizontal(self):
        """
        Test the extraction of a short text file in a medium, using a horizontal raster scan.
        """
        sourcePath = 'files/mona_small_h' + self.ext
        expectedPath = 'files/small.txt'

        medium = Steganography(sourcePath)
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(
            self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
Exemple #26
0
    def test_extractLongTextVertical(self):
        """
        Test the extraction of a long text file in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/lena_full_v' + self.ext
        expectedPath = 'files/full.txt'

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(
            self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
Exemple #27
0
    def test_extractColorImageVertical(self):
        """
        Test the extraction of a color in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/nature_sunflower_v' + self.ext
        expectedPath = 'files/sunflower' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #28
0
def encProcess(ruid,encfile,enc_opf,img,emkey,out_f,cframe,nframe):
	print('[INFO] STARTING ENCRYPTION PROCESS.')
	encrytor = Encryption(encfile)
	enc_key = encrytor.encrypt_data(enc_opf)
	print('[INFO] ENCRYPTION COMPLETED SUCCESSFULLY.')
	print('[INFO] LOADING SOURCE IMAGE')
	in_im = cv2.imread(img)
	print('[INFO] SOURCE IMAGE LOADED SUCCESSFULLY.')
	print('[INFO] STARTING STEGANOGRAPHY PROCESS.')
	stegano = Steganography(in_im,emkey)
	res_img = stegano.encode_data(enc_key,ruid)
	cv2.imwrite(out_f,res_img)
	print('[INFO] STEGANOGRAPHY PROCESS COMPLETED SUCCESSFULLY.')
	tkinter.messagebox.showinfo("Success", "Encrypted File and Steganographied Image Saved.")
	showPrev(cframe,nframe)
Exemple #29
0
    def test_extractGrayImageVertical(self):
        """
        Test the extraction of a gray-scale in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/bridge_dog_v' + self.ext
        expectedPath = 'files/dog' + self.ext

        medium = Steganography(sourcePath, direction='vertical')
        message = medium.extractMessageFromMedium()
        message.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_embedGrayImageVertical(self):
        """
        Test the embedding of a gray-scale image in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/dog' + self.ext
        expectedPath = 'files/bridge_dog_v' + self.ext
        mediumPath = 'files/bridge' + self.ext

        message = Message(filePath=sourcePath, messageType='GrayImage')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #31
0
    def test_embedColorImageVertical(self):
        """
        Test the embedding of a color image in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/sunflower' + self.ext
        expectedPath = 'files/nature_sunflower_v' + self.ext
        mediumPath = 'files/nature' + self.ext

        message = Message(filePath=sourcePath, messageType='ColorImage')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #32
0
    def test_embedGrayImageVertical(self):
        """
        Test the embedding of a gray-scale image in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/dog' + self.ext
        expectedPath = 'files/bridge_dog_v' + self.ext
        mediumPath = 'files/bridge' + self.ext

        message = Message(filePath=sourcePath, messageType='GrayImage')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_extractEncryptedText(self):
        """
        Test the extraction of an encrypted text file in a medium.
        """
        sourcePath = 'files/lena_full_enc' + self.ext
        expectedPath = 'files/full.txt'

        medium = Steganography(sourcePath)
        extractedMessage = medium.extractMessageFromMedium()

        encryptedMessage = AesMessage(extractedMessage, self.password)
        encryptedMessage.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
    def test_extractEncryptedColorImage(self):
        """
        Test the extraction of an encrypted color image `in a medium.
        """
        sourcePath = 'files/bridge_color_mona_enc' + self.ext
        expectedPath = 'files/color_mona' + self.ext

        medium = Steganography(sourcePath)
        extractedMessage = medium.extractMessageFromMedium()

        encryptedMessage = AesMessage(extractedMessage, self.password)
        encryptedMessage.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #35
0
    def test_embedShortTextVertical(self):
        """
        Test the embedding of a short text file in a medium, using a vertical raster scan.
        """
        sourcePath = 'files/small.txt'
        expectedPath = 'files/mona_small_v' + self.ext
        mediumPath = 'files/mona' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        medium = Steganography(mediumPath, direction='vertical')
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #36
0
    def test_embedLongTextHorizontal(self):
        """
        Test the embedding of a long text file in a medium, using a horizontal raster scan.
        """
        sourcePath = 'files/full.txt'
        expectedPath = 'files/lena_full_h' + self.ext
        mediumPath = 'files/lena' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(message, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #37
0
    def test_extractEncryptedColorImage(self):
        """
        Test the extraction of an encrypted color image `in a medium.
        """
        sourcePath = 'files/bridge_color_mona_enc' + self.ext
        expectedPath = 'files/color_mona' + self.ext

        medium = Steganography(sourcePath)
        extractedMessage = medium.extractMessageFromMedium()

        encryptedMessage = AesMessage(extractedMessage, self.password)
        encryptedMessage.saveToTarget(self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #38
0
def decode_stegano():
	os.system('clear')
	print('Starting Steganography Decoding Process') 
	in_f = input('Encoded image (shoule be .png format)\t: ')
	in_im = cv2.imread(in_f)
	key = input('Steganography Encoding key (Caution: sensitive information)\t: ')
	stegano = Steganography(in_im,key)
	ruid = stegano.extract_receiver()
	print('meant for '+str(ruid))
	if(auth(ruid)):
		
		byte_lst = stegano.decode_data()
		data = bytes(byte_lst)
		return data
	else:
		print('not authorized')
		return None
    def test_embedEncryptedText(self):
        """
        Test the embedding of an encrypted text file in a medium.
        """
        sourcePath = 'files/full.txt'
        expectedPath = 'files/lena_full_enc' + self.ext
        mediumPath = 'files/lena' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        encryptedMessage = AesMessage(message, self.password)

        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(encryptedMessage, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
    def test_embedEncryptedColorImage(self):
        """
        Test the embedding of an encrypted color image in a medium.
        """
        sourcePath = 'files/color_mona' + self.ext
        expectedPath = 'files/bridge_color_mona_enc' + self.ext
        mediumPath = 'files/bridge' + self.ext

        message = Message(filePath=sourcePath, messageType='ColorImage')
        encryptedMessage = AesMessage(message, self.password)

        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(encryptedMessage, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #41
0
    def test_extractEncryptedText(self):
        """
        Test the extraction of an encrypted text file in a medium.
        """
        sourcePath = 'files/lena_full_enc' + self.ext
        expectedPath = 'files/full.txt'

        medium = Steganography(sourcePath)
        extractedMessage = medium.extractMessageFromMedium()

        encryptedMessage = AesMessage(extractedMessage, self.password)
        encryptedMessage.saveToTarget(self.targetTextFilePath)

        actualTextFile, expectedTextFile = loadTwoTextFiles(
            self.targetTextFilePath, expectedPath)

        self.assertEqual(actualTextFile, expectedTextFile)
Exemple #42
0
    def test_embedEncryptedText(self):
        """
        Test the embedding of an encrypted text file in a medium.
        """
        sourcePath = 'files/full.txt'
        expectedPath = 'files/lena_full_enc' + self.ext
        mediumPath = 'files/lena' + self.ext

        message = Message(filePath=sourcePath, messageType='Text')
        encryptedMessage = AesMessage(message, self.password)

        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(encryptedMessage, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
Exemple #43
0
    def test_embedEncryptedColorImage(self):
        """
        Test the embedding of an encrypted color image in a medium.
        """
        sourcePath = 'files/color_mona' + self.ext
        expectedPath = 'files/bridge_color_mona_enc' + self.ext
        mediumPath = 'files/bridge' + self.ext

        message = Message(filePath=sourcePath, messageType='ColorImage')
        encryptedMessage = AesMessage(message, self.password)

        medium = Steganography(mediumPath)
        medium.embedMessageInMedium(encryptedMessage, self.targetImageFilePath)

        actualImage, expectedImage = loadTwoImageFiles(
            self.targetImageFilePath, expectedPath)

        self.assertEqual(actualImage, expectedImage)
	def decrypt(self,scandir,outfile, msgtype, cypherkey='VignereCypher'):	
		""" Decrypts the message stores in the file. It inherits most of its functionality from the parents class. It checks if we are storing an image or a text file. It appends .txt or .tif to the file accordingly. It just returns the message if its a text file. If its an image, grayscale value are appended to the array and image is then saved in the output files. The user also sends the file type, "I" for image and "T" for text.

Examples: a.decrypt("H", outfile, "I"), a.decrypt("V", outfile, "T", "KEY"),

 """	
		embedata = Steganography.decrypt(self, scandir, cypherkey)
		ftype = ""
		for i in range(0, 3):
			ftype = ftype + embedata[i]
		if((ftype == "msg" and msgtype != 'T') or (ftype == "img" and msgtype != 'I')):
			raise ValueError("The type of file that was provided does not match the data embedded")
		if ftype == "msg":
			data = ''
			for i in range(3, len(embedata)):
				data = data + embedata[i]
			if not(re.search(".txt$", outfile)):
				outfile = outfile + ".txt"
			try:
				fh = open(outfile,"w")
				fh.write(data)
				fh.close()
				
			except:
				raise ValueError("Path provided to the output file does not exist.")

		if ftype == "img":
			a = re.search("[(](?P<hor>[\d]+), (?P<ver>[\d]+)[)]", embedata)
			hor = a.group("hor")
			ver = a.group("ver")
			omitstrlen = 4 + 3 + len(hor) + len(ver)
			newstr = ""
			for i in range(omitstrlen, len(embedata)):
				newstr = newstr + embedata[i]
			hor = int(hor)
			ver = int(ver)
			count = 0

			picarray = []
			for x in range(0, hor):
				for y in range(0, ver):
					picarray.append(ord(newstr[count]))		
					count += 1
			im = Image.new('L', (hor,ver))
			im.putdata(picarray)
			if not(re.search(".tif$", outfile)):
				outfile = outfile + ".tif"
			try:
				im.save(outfile)
			except:
				raise ValueError("Path provided to the output file does not exist.")

		return True		
Exemple #45
0
    def test_embedLargeMessageInSmallMedium(self):
        """
        Test that trying to embed a large message in medium, produces an exception.
        """
        sourcePath = 'files/sunflower' + self.ext
        mediumPath = 'files/mona' + self.ext

        message = Message(filePath=sourcePath, messageType='ColorImage')
        medium = Steganography(mediumPath)

        self.assertRaises(ValueError, medium.embedMessageInMedium, message,
                          self.targetImageFilePath)
	def __init__(self, imgname):
		Steganography.__init__(self, imgname)
	def wipealldata(self):
		Steganography.wipealldata(self)	
	def encrypt(self,inputname,scandir='H',cypherkey="VignereCypher", fname="encrypted.tif"):
		""" This is one of the main functions that a user can use. It inherits some functionality from the Steganography encrypt. The user passes a file and we check if the file is a text file, it just calls the parent class encrypt function and that does the embedding. If it is an image that we need to embed, it converts the grayscale value to a character and then embeds it, the functionality could not be invoked from the parents class as in the initial class, all characters have to have an ascii value under 128 but in this case it can go uptil 255. A file name can be given to store the new image
		Examples: a.encrypt((textfile), a.encrypt(imgf, "V"), a.encrypt(img, "H", ""), a.encrypt(textfile, "V", "SECURITYKEY", "newimg.tif")"""
		try:
			fh = open(inputname)
		except:
			raise ValueError("Source file path provided was wrong.")
		itype = 1
		if(re.search(".txt$", inputname)):
			itype = 2
			try:
				all = fh.readlines()
				new = "".join(all)
			except:
				raise ValueError("Text File doesn not exist")
			message = "msg" + new	
			Steganography.encrypt(self, message, scandir, cypherkey, fname)

		#Checks what file is given
		elif(re.search(".tif$", inputname)):
			if(scandir == 'H'):
				typeofscan = 1
			elif(scandir == 'V'):
				typeofscan = 2
			else:
				raise ValueError("Scan Direction can only be 'H' or 'V', where H is horizontal and V is vertical")
			try:
				inimg = Image.open(inputname)
				inpic = inimg.load()
				imgarr = inimg.size
			except:
				raise ValueError("Image does not exist")
			lensi = 0
			for i in imgarr:
				lensi = lensi + len(str(i))

			init = "$a$a$"
			if not(type(inpic[0,0]) is int):
				raise ValueError("File provided is a color image.")
			message = init + "img"
			newstr = ""
			message = message + str(imgarr)
			for i in range(len(message)):
				newstr = newstr + '{0:08b}'.format(ord(message[i]))
			message = newstr
			grysc = 0
			if(type(self.pic[0,0]) is int):
				grysc = 1
			for y in range(0, imgarr[0]):
				for x in range(0, imgarr[1]):
					new = '{0:08b}'.format(inpic[x,y])
					message = message + new
			#Converts the grayscale value to a character and then to its binary value
			for i in range(len(init)):
				message = message + '{0:08b}'.format(ord(init[i]))
			imgarr = self.img.size
			if(grysc == 1):
				msgsize1 = ((imgarr[0] * imgarr[1] * 1))
			else:
				msgsize1 = ((imgarr[0] * imgarr[1] * 3))
			if(msgsize1 < len(message)):
				raise ValueError("Image can not be embedded as it is too big")
			newstr = message	
			noftimes = len(newstr)
			count = 0
			if(typeofscan == 1):
				for y in range(0, imgarr[1]):
					for x in range(0, imgarr[0]):
						if(count != (noftimes)):
							count = ExtendedStegano._valchange(self,x,y,newstr,grysc,count,noftimes)
						else:
							self.img.save(fname)
							return True
			elif(typeofscan == 2):
				for x in range(0, imgarr[0]):
					for y in range(0,imgarr[1]):
						if(count != (noftimes)):
							count = ExtendedStegano._valchange(self,x,y,newstr,grysc,count, noftimes)
						else:
							self.img.save(fname)
							return True
		else:
			raise ValueError("The file provided isn't one of the acceptable input types.")
def unmerge(img, output):
    unmerged_image = Steganography.unmerge(Image.open(img))
    unmerged_image.save(output)
def merge(img1, img2, output):
    merged_image = Steganography.merge(Image.open(img1), Image.open(img2))
    merged_image.save(output)