Fixed and rename image steg delimeter, able to take in large text data.

This commit is contained in:
devoalda 2023-05-22 12:05:57 +08:00
parent 570f26e4f4
commit da558b7ca1
1 changed files with 45 additions and 24 deletions

View File

@ -4,8 +4,16 @@ import numpy as np
class img_steg: class img_steg:
def __init__(self, image_name: str = "image.png", bit_to_hide: int = 2): def __init__(self, image_name: str = "image.png", bit_to_hide: int = 2):
"""
Initialize the class
:param image_name: Name of the image to encode or decode
:type image_name: str
:param bit_to_hide: Bit to hide the data in (1 - LSB to 8 - MSB)
:type bit_to_hide: int
"""
self.image_name = image_name self.image_name = image_name
self.bit_to_hide = bit_to_hide self.bit_to_hide = 8 - bit_to_hide
self.delimiter = "\n"
def to_bin(self, data: str) -> str | list[str]: def to_bin(self, data: str) -> str | list[str]:
""" """
@ -36,16 +44,17 @@ class img_steg:
""" """
return ''.join([chr(int(data[i:i + 8], 2)) for i in range(0, len(data), 8)]) return ''.join([chr(int(data[i:i + 8], 2)) for i in range(0, len(data), 8)])
def decode(self): def decode(self) -> str:
""" """
Decode the data hidden in the image Decode the data hidden in the image
Returns: Args:
Decoded Data: str None
:return: Decoded Data: String
""" """
print("[+] Decoding...") print("[+] Decoding...")
image = cv2.imread(self.image_name) # read image image = cv2.imread(self.image_name) # read image
binary_data = "" binary_data = ""
bit_to_hide = self.bit_to_hide - 1 bit_to_hide = self.bit_to_hide
for row in image: for row in image:
for pixel in row: for pixel in row:
r, g, b = self.to_bin(pixel) r, g, b = self.to_bin(pixel)
@ -56,8 +65,10 @@ class img_steg:
all_bytes = [binary_data[i: i + 8] for i in range(0, len(binary_data), 8)] all_bytes = [binary_data[i: i + 8] for i in range(0, len(binary_data), 8)]
# Convert from bits to characters # Convert from bits to characters
decoded_data = self.from_bin(''.join(all_bytes)) decoded_data = self.from_bin(''.join(all_bytes))
if decoded_data.endswith("===="): if decoded_data.endswith(self.delimiter):
decoded_data = decoded_data[:-4] decoded_data = decoded_data[:-4]
decoded_data = decoded_data.split(self.delimiter)[0]
return decoded_data return decoded_data
def encode(self, secret_data: str = "Hello World") -> np.ndarray: def encode(self, secret_data: str = "Hello World") -> np.ndarray:
@ -72,14 +83,13 @@ class img_steg:
image = cv2.imread(self.image_name) # read image image = cv2.imread(self.image_name) # read image
n_bytes = image.shape[0] * image.shape[1] * 3 // 8 # Max bytes to encode n_bytes = image.shape[0] * image.shape[1] * 3 // 8 # Max bytes to encode
print("[*] Maximum bytes to encode:", n_bytes) print("[*] Maximum bytes to encode:", n_bytes)
secret_data += "====" # Stopping Criteria secret_data += self.delimiter # Add delimiter at the end of data
if len(secret_data) > n_bytes: if len(secret_data) > n_bytes:
raise ValueError("[!] Insufficient bytes, need a bigger image or less data") raise ValueError("[!] Insufficient bytes, need a bigger image or less data")
print("[*] Encoding Data...") print("[*] Encoding Data...")
# Convert bit to hide position # Convert bit to hide position
# bit_to_hide = 2 - self.bit_to_hide bit_to_hide = self.bit_to_hide
bit_to_hide = self.bit_to_hide - 1
data_index = 0 data_index = 0
binary_secret_data = self.to_bin(secret_data) # Convert data to binary binary_secret_data = self.to_bin(secret_data) # Convert data to binary
data_len = len(binary_secret_data) # size of data to hide data_len = len(binary_secret_data) # size of data to hide
@ -113,27 +123,38 @@ def main():
if choice == 1: if choice == 1:
image_name = input("Enter name of image to encode: ") image_name = input("Enter name of image to encode: ")
secret_data = input("Enter data to encode: ") secret_data = input("Enter data to encode: ")
bit_to_hide = int(input("Enter bit to hide (1-8): ")) bit_to_hide = int(input("Enter bit to hide (1 - LSB to 8 - MSB): "))
encoded_image = img_steg(image_name, bit_to_hide).encode(secret_data) encoded_image = img_steg(image_name, bit_to_hide).encode(secret_data)
cv2.imwrite("encoded_image.png", encoded_image) extension = image_name.split(".")[-1]
cv2.imwrite("encoded_image." + extension, encoded_image)
print("Image Encoded Successfully") print("Image Encoded Successfully")
elif choice == 2: elif choice == 2:
image_name = input("Enter name of image to decode: ") image_name = input("Enter name of image to decode: ")
bit_to_hide = int(input("Enter bit to hide (1-8): ")) bit_to_hide = int(input("Enter bit to hide (1 - LSB to 8 - MSB): "))
decoded_data = img_steg(image_name, bit_to_hide).decode() decoded_data = img_steg(image_name, bit_to_hide).decode()
print("Decoded Data:", decoded_data) # Still returns special chars and ==== at the end print("Decoded Data:", decoded_data)
if __name__ == "__main__": if __name__ == "__main__":
main() main()
# FOR REFERENCE ##############################
# Welcome to Image Steganography # _ _
# 1. Encode # | | | |___ __ _ __ _ ___
# 2. Decode # | | | / __|/ _` |/ _` |/ _ \
# 3. Exit # | |_| \__ \ (_| | (_| | __/
# Enter your choice: 2 # \___/|___/\__,_|\__, |\___|
# Enter name of image to decode: encoded_image.png # |___/
# Enter bit to hide (1-8): 5 ##############################
# [+] Decoding... #
# Decoded Data: abc123abcasdf==== # Initialise class with image name and bit to hide
#
# image_name = image name with extension (String)
# bit_to_hide = bit to hide the data in (1 - LSB to 8 - MSB) (int)
#
# To encode:
# encoded_image = img_steg(image_name, bit_to_hide).encode(secret_data)
#
# To decode:
# decoded_data = img_steg(image_name, bit_to_hide).decode()
# Both are string types