Question

In: Computer Science

Provide a detailed code for Double Encryption using Image Steganography in PYTHON First encrypt the data(using...

Provide a detailed code for Double Encryption using Image Steganography in PYTHON

First encrypt the data(using RC4/AES algorithm) before storing it in the image, after encrypted data is stored in the image, use image steganography to encrypt the image. Hence, we are using double encryption

Solutions

Expert Solution

#import all the required libraries

import cv2
import numpy as np
import types
from google.colab.patches import cv2_imshow #Google colab crashes if you try to display 
#image using cv2.imshow() thus use this import


def messageToBinary(message):
  if type(message) == str:
    return ''.join([ format(ord(i), "08b") for i in message ])
  elif type(message) == bytes or type(message) == np.ndarray:
    return [ format(i, "08b") for i in message ]
  elif type(message) == int or type(message) == np.uint8:
    return format(message, "08b")
  else:
    raise TypeError("Input type not supported")

# Function to hide the secret message into the image

def hideData(image, secret_message):

  # calculate the maximum bytes to encode
  n_bytes = image.shape[0] * image.shape[1] * 3 // 8
  print("Maximum bytes to encode:", n_bytes)

  #Check if the number of bytes to encode is less than the maximum bytes in the image
  if len(secret_message) > n_bytes:
      raise ValueError("Error encountered insufficient bytes, need bigger image or less data !!")
  
  secret_message += "#####" # you can use any string as the delimeter

  data_index = 0
  # convert input data to binary format using messageToBinary() fucntion
  binary_secret_msg = messageToBinary(secret_message)

  data_len = len(binary_secret_msg) #Find the length of data that needs to be hidden
  for values in image:
      for pixel in values:
          # convert RGB values to binary format
          r, g, b = messageToBinary(pixel)
          # modify the least significant bit only if there is still data to store
          if data_index < data_len:
              # hide the data into least significant bit of red pixel
              pixel[0] = int(r[:-1] + binary_secret_msg[data_index], 2)
              data_index += 1
          if data_index < data_len:
              # hide the data into least significant bit of green pixel
              pixel[1] = int(g[:-1] + binary_secret_msg[data_index], 2)
              data_index += 1
          if data_index < data_len:
              # hide the data into least significant bit of  blue pixel
              pixel[2] = int(b[:-1] + binary_secret_msg[data_index], 2)
              data_index += 1
          # if data is encoded, just break out of the loop
          if data_index >= data_len:
              break

  return image

def showData(image):

  binary_data = ""
  for values in image:
      for pixel in values:
          r, g, b = messageToBinary(pixel) #convert the red,green and blue values into binary format
          binary_data += r[-1] #extracting data from the least significant bit of red pixel
          binary_data += g[-1] #extracting data from the least significant bit of red pixel
          binary_data += b[-1] #extracting data from the least significant bit of red pixel
  # split by 8-bits
  all_bytes = [ binary_data[i: i+8] for i in range(0, len(binary_data), 8) ]
  # convert from bits to characters
  decoded_data = ""
  for byte in all_bytes:
      decoded_data += chr(int(byte, 2))
      if decoded_data[-5:] == "#####": #check if we have reached the delimeter which is "#####"
          break
  #print(decoded_data)
  return decoded_data[:-5] #remove the delimeter to show the original hidden message


# Encode data into image 
def encode_text(): 
  image_name = input("Enter image name(with extension): ") 
  image = cv2.imread(image_name) # Read the input image using OpenCV-Python.
  #It is a library of Python bindings designed to solve computer vision problems. 
  
  #details of the image
  print("The shape of the image is: ",image.shape) #check the shape of image to calculate the number of bytes in it
  print("The original image is as shown below: ")
  resized_image = cv2.resize(image, (500, 500)) #resize the image as per your requirement
  cv2_imshow(resized_image) #display the image
  
      
  data = input("Enter data to be encoded : ") 
  if (len(data) == 0): 
    raise ValueError('Data is empty')
  
  filename = input("Enter the name of new encoded image(with extension): ")
  encoded_image = hideData(image, data) # call the hideData function to hide the secret message into the selected image
  cv2.imwrite(filename, encoded_image)

# Decode the data in the image 
def decode_text():
  # read the image that contains the hidden image
  image_name = input("Enter the name of the steganographed image that you want to decode (with extension) :") 
  image = cv2.imread(image_name) #read the image using cv2.imread() 

  print("The Steganographed image is as shown below: ")
  resized_image = cv2.resize(image, (500, 500))  #resize the original image as per your requirement
  cv2_imshow(resized_image) #display the Steganographed image
    
  text = showData(image)
  return text

# Image Steganography         
def Steganography(): 
    a = input("Image Steganography \n 1. Encode the data \n 2. Decode the data \n Your input is: ")
    userinput = int(a)
    if (userinput == 1):
      print("\nEncoding....")
      encode_text() 
          
    elif (userinput == 2):
      print("\nDecoding....") 
      print("Decoded message is " + decode_text()) 
    else: 
        raise Exception("Enter correct input") 
          
Steganography() #encode image

Steganography() #decode image

I have done this in jupyter notebook see the below screenshots


Related Solutions

Write a small program to encrypt and decrypt a message using Python library.
Write a small program to encrypt and decrypt a message using Python library.
I need the code in python where I can encrypt and decrypt any plaintext. For example,...
I need the code in python where I can encrypt and decrypt any plaintext. For example, the plaintext "hello" from each of these Block Cipher modes of Operation. Electronic Code Block Mode (ECB) Cipher block Mode (CBC) Cipher Feedback Mode (CFB) Output feedback Mode (OFB) Counter Mode (CTR) Here is an example, Affine cipher expressed in C. Encryption: char cipher(unsigned char block, char key) { return (key+11*block) } Decryption: char invcipher(unsigned char block, char key) { return (163*(block-key+256)) }
How do I implement Image Processing using VHDL for FPGA? Please provide VHDL code
How do I implement Image Processing using VHDL for FPGA? Please provide VHDL code
Using Python, write a simple application that takes user input of plaintext and key, and encrypt...
Using Python, write a simple application that takes user input of plaintext and key, and encrypt the plaintext with Vigenere Cipher. The application should then print out the plaintext and the ciphertext.
In simple python code 1) Write a function to convert the image to grayscale. 2Write a...
In simple python code 1) Write a function to convert the image to grayscale. 2Write a function to convert an image to black and white 3)Sepia Tone images are those brownish colored images that may remind you of times past. The formula for creating a sepia tone is as follows: newR = (R × 0.393 + G × 0.769 + B × 0.189) newG = (R × 0.349 + G × 0.686 + B × 0.168) newB = (R ×...
Using cImage in Python, how to create an image of a sunset (at least 400 by...
Using cImage in Python, how to create an image of a sunset (at least 400 by 400 pixels), black at the top, becoming redder/yellower lower down. Also, randomly place in the sky a given number of white stars of random size of either one pixel or 4 (adjacent) pixels
Project on a double pendulum using MATLAB. I have simulated double pendulum chaos using the code...
Project on a double pendulum using MATLAB. I have simulated double pendulum chaos using the code I found in Chegg. Could you please guide in adding a code to determine the time it takes for the second arm of the pendulum to "flip" based on initial starting conditions?
Use python programming to write this code and provide a screen short for the code. 2....
Use python programming to write this code and provide a screen short for the code. 2. Write a function that takes one argument (a string) and returns a string consisting of the single character from that string with the largest value. Your function should contain a for loop. You can assume that the input to your function will always be a valid string consisting of at least one character. You can assume that the string will consist only of lower-case...
Python 3 Fix the code. It is not saving the data into the xls file Code:...
Python 3 Fix the code. It is not saving the data into the xls file Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Working product").grid(row=4, sticky="W", pady=20, padx=20) #Working product label tk.Label(window, text="Failed...
***Please code in Python Write another code Newton (in double precision) implementing the Newton-Raphson Method   (copy...
***Please code in Python Write another code Newton (in double precision) implementing the Newton-Raphson Method   (copy your Bisect code and modify).   Evaluation of F(x) and F'(x) should be done in a subprogram FCN(x).   The code should ask for input of: x0, TOL, maxIT (and should print output similar to Bisect code).   Debug on a simple problem, like x2−3 = 0.   Then use it to find root of F(x) in [1,2] with TOL=1.e-12. Now consider the problem of finding zeros of      ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT