程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to hide data in an image using Python

編輯:Python

Steganography is the art of hiding secret data in any file .

Secret data can be data in any format , Such as text or even files . In short , The main purpose of steganography is to hide any file ( It's usually an image 、 Audio or video ) Expected information in , Without actually changing the appearance of the file , That is, the appearance of the file looks the same as before .

In this article , We will focus on Image-based steganography , That is to hide secret data in the image .

But before further study , Let's first look at what the image is made of :

  1. Pixels are part of an image .
  2. Each pixel contains three values :( Red 、 green 、 Blue ) Also known as RGB value .
  3. Every RGB Values range from 0 To 255.

Now? , Let's see how to encode and decode data into our images .

code

There are many algorithms that can be used to encode data into images , In fact, we can also make one by ourselves . The algorithm used in this article is easy to understand and implement .

Algorithm is as follows :

  1. For each character in the data , Put it ASCII Value to 8 Bit binary [1].
  2. Read three pixels at a time , Its total RGB The value is 3*3=9 individual . Top eight RGB Value is used to store a conversion to 8 Binary characters .
  3. Compare corresponding RGB Values and binary data . If the binary number is 1, be RGB Values will be converted to odd numbers , Otherwise it's even .
  4. The first 9 Values determine whether more pixels should be read . If there is more data to read , Namely encoding or decoding , Is the first 9 Pixels become even ; otherwise , If we want to stop reading pixels further , Then make it odd .

Repeat the process , Until all the data is encoded into the image .

Example

Suppose the message to be hidden is ‘Hii’.

The message is three bytes , therefore , The pixels required to encode the data are 3 x 3 = 9. Consider one 4 x 3 Image , All in all 12 Pixel , This is enough to encode the given data .

[(27, 64, 164), (248, 244, 194), (174, 246, 250), (149, 95, 232),
(188, 156, 169), (71, 167, 127), (132, 173, 97), (113, 69, 206),
(255, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]

The first 1 Step

H Of ASCII The value is 72 , Its binary equivalent value is 01001000 .

The first 2 Step

Read the first three pixels .

(27, 64, 164), (248, 244, 194), (174, 246, 250)

The first 3 Step

Now? , Change the pixel value to an odd number of 1, Even is 0, Just like in binary equivalent data .

for example , The first binary number is 0, first RGB The value is 27 , It needs to be converted to an even number , It means 26 . Similarly ,64 Converted to 63 Because the next binary number is 1 therefore RGB The value should be odd .

therefore , The modified pixel is :

(26, 63, 164), (248, 243, 194), (174, 246, 250)

The first 4 Step

Because we have to encode more data , So the last value should be even . Again ,i You can encode in this image .

Through execution +1 or -1 Make the pixel value odd / Even number , We should pay attention to binary conditions . That is, the pixel value should be greater than or equal to 0 And less than or equal to 255 .

The new image will look like this :

[(26, 63, 164), (248, 243, 194), (174, 246, 250), (148, 95, 231),
(188, 155, 168), (70, 167, 126), (132, 173, 97), (112, 69, 206),
(254, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]

decode

For decoding , We will try to find out how to reverse the algorithm we used to encode data .

  1. Again , Read three pixels at a time . front 8 individual RGB Value provides us with information about confidential data , The first 9 A value tells us whether to move forward .
  2. For the first eight values , If the value is odd , Then the binary bit is 1 , Otherwise 0 .
  3. These bits are concatenated into a string , Every three pixels , We get a byte of secret data , This means one character .
  4. Now? , If the first 9 The values are even , So let's continue reading three pixels at a time , otherwise , Let's stop .

for example

Let's start reading three pixels at a time .

Consider the image we encoded before .

[(26, 63, 164), (248, 243, 194), (174, 246, 250), (148, 95, 231),
(188, 155, 168), (70, 167, 126), (132, 173, 97), (112, 69, 206),
(254, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]

The first 1 Step

We first read three pixels :

[(26, 63, 164), (248, 243, 194), (174, 246, 250)

The first 2 Step

Read the first value :26, It's an even number , So the binary bit is 0 . Similarly , about 63 , The binary bit is 1 , about 164 It is 0 . This process continues until 8 individual RGB value .

The first 3 Step

After connecting all binary values , We finally get binary values :01001000. The final binary data corresponds to the decimal value 72, stay ASCII in , It represents characters H .

The first 4 Step

Due to the first 9 The values are even , We repeat the above steps . When you encounter the first 9 When a value is an odd number , Let's stop .

result , We got the original information , namely Hii .

Of the above algorithm Python The procedure is as follows :

# Python program implementing Image Steganography
# PIL module is used to extract
# pixels of image and modify it
from PIL import Image
# Convert encoding data into 8-bit binary
# form using ASCII value of characters
def genData(data):
# list of binary codes
# of given data
newd = []
for i in data:
newd.append(format(ord(i), '08b'))
return newd
# Pixels are modified according to the
# 8-bit binary data and finally returned
def modPix(pix, data):
datalist = genData(data)
lendata = len(datalist)
imdata = iter(pix)
for i in range(lendata):
# Extracting 3 pixels at a time
pix = [value for value in imdata.__next__()[:3] +
imdata.__next__()[:3] +
imdata.__next__()[:3]]
# Pixel value should be made
# odd for 1 and even for 0
for j in range(0, 8):
if (datalist[i][j] == '0' and pix[j]% 2 != 0):
pix[j] -= 1
elif (datalist[i][j] == '1' and pix[j] % 2 == 0):
if(pix[j] != 0):
pix[j] -= 1
else:
pix[j] += 1
# pix[j] -= 1
# Eighth pixel of every set tells
# whether to stop ot read further.
# 0 means keep reading; 1 means thec
# message is over.
if (i == lendata - 1):
if (pix[-1] % 2 == 0):
if(pix[-1] != 0):
pix[-1] -= 1
else:
pix[-1] += 1
else:
if (pix[-1] % 2 != 0):
pix[-1] -= 1
pix = tuple(pix)
yield pix[0:3]
yield pix[3:6]
yield pix[6:9]
def encode_enc(newimg, data):
w = newimg.size[0]
(x, y) = (0, 0)
for pixel in modPix(newimg.getdata(), data):
# Putting modified pixels in the new image
newimg.putpixel((x, y), pixel)
if (x == w - 1):
x = 0
y += 1
else:
x += 1
# Encode data into image
def encode():
img = input("Enter image name(with extension) : ")
image = Image.open(img, 'r')
data = input("Enter data to be encoded : ")
if (len(data) == 0):
raise ValueError('Data is empty')
newimg = image.copy()
encode_enc(newimg, data)
new_img_name = input("Enter the name of new image(with extension) : ")
newimg.save(new_img_name, str(new_img_name.split(".")[1].upper()))
# Decode the data in the image
def decode():
img = input("Enter image name(with extension) : ")
image = Image.open(img, 'r')
data = ''
imgdata = iter(image.getdata())
while (True):
pixels = [value for value in imgdata.__next__()[:3] +
imgdata.__next__()[:3] +
imgdata.__next__()[:3]]
# string of binary data
binstr = ''
for i in pixels[:8]:
if (i % 2 == 0):
binstr += '0'
else:
binstr += '1'
data += chr(int(binstr, 2))
if (pixels[-1] % 2 != 0):
return data
# Main Function
def main():
a = int(input(":: Welcome to Steganography ::\n"
"1. Encode\n2. Decode\n"))
if (a == 1):
encode()
elif (a == 2):
print("Decoded Word : " + decode())
else:
raise Exception("Enter correct input")
# Driver Code
if __name__ == '__main__' :
# Calling main function
main()

The modules used in the program are PIL , It represents Python Image library , It enables us to Python Perform operations on images in .

Program execution

Data encoding

Data decoding

The input image

Output image

limitations

The program may not be able to JPEG The image is processed as expected , because JPEG Use lossy compression , This means modifying pixels to compress the image and reduce quality , Therefore, data loss will occur .

Reference resources

  1. https://www.geeksforgeeks.org/program-decimal-binary-conversion/
  2. https://www.geeksforgeeks.org/working-images-python/
  3. https://dev.to/erikwhiting88/let-s-hide-a-secret-message-in-an-image-with-python-and-opencv-1jf5
  4. A code along with the dependencies can be found here: https://github.com/goelashwin36/image-steganography

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved