用于Python中图像Stenography的BMP文件中的LSB加密

时间:2017-11-25 23:54:42

标签: python encryption bmp

我希望用Python将秘密消息加密到BMP文件中。我有一个解密和正常工作的程序(使用提供的图像测试)。然而,加密让我很难过。

我已经编写了以下代码,该代码应该将BMP文件中像素数据的最低有效位取出并修改它以匹配秘密消息中的位。

我认为当我保存文件(可能基于操作系统或硬件)时,会有一些事情发生,这会比在Windows上保存BMP的方式不同。或者我写错了,因为解密后没有出现消息。

我在这里缺少什么?

from PIL import Image
from bitstring import BitArray
import binascii
import os
import io

#Create a secret message
message = "This is my secret message"

#Convert the secret message to binary
message = ' '.join(format(ord(x), 'b') for x in message)

# Open the Image of choice, Dump all binary of BMP file
with open("barbara_gray.bmp", "rb") as imageFile:
    f = imageFile.read()
    b = bytearray(f)

# BMP Header size (start of pixel data)
BMP_Header_End = 54

# Count to keep track of where we are in the secret message
count = 0

# Variable to store bit data
bit = ""

# For the total length of the secret message
for i in range(BMP_Header_End, BMP_Header_End + len(message)):
    print(count)
    # Get the LSB of the image file byte
    bit = str(b[i] & 1)

    # If the LSB is not equal to the bit of the message
    if bit != message[count]:

        # Change the byte value by 1 (effectively changing the LSB by 1)
        if b[i] == 255:
            b[i] = b[i] - 1
        else:
            b[i] = b[i] + 1

    # Move to the next character in the message
    count += 1
print(b[54:])

# Write the binary to an image file
image = Image.open(io.BytesIO(b))
image.save('my_image.bmp', 'bmp')

0 个答案:

没有答案