【笔记】Python3实现png图片的隐写术

前言

Python3实现png图片的隐写术

下载依赖

1
2
3
4
python3.9 -m venv venv
source venv/bin/activate
pip install Pillow
pip install docopt

源代码

main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
# coding=utf-8

"""Encode png image via command-line.

Usage:
main (-e|encode) <originImage> [<text>] [<encoded_image>]
main (-d|decode) <encoded_image>

Options:
-h,--help 显示帮助菜单
-e 加密
-d 解密

Example:
main -e coffee.png hello textOrFileToEncode encoded_image.png
main -d encoded_image.png
"""

from PIL import Image
from docopt import docopt


# 取得一个 PIL 图像并且更改所有值为偶数(使最低有效位为 0)
def rgba_make_image_even(image):
# 得到一个这样的列表: [(r,g,b,t),(r,g,b,t)...]
pixels = list(image.getdata())
# 更改所有值为偶数(魔法般的移位)
even_pixels = [(r >> 1 << 1, g >> 1 << 1, b >> 1 << 1, t >> 1 << 1) for [r, g, b, t] in pixels]
# 创建一个相同大小的图片副本
even_image = Image.new(image.mode, image.size)
# 把上面的像素放入到图片副本
even_image.putdata(even_pixels)
return even_image


# 取得一个 PIL 图像并且更改所有值为偶数(使最低有效位为 0)
def rgb_make_image_even(image):
# 得到一个这样的列表: [(r,g,b,t),(r,g,b,t)...]
pixels = list(image.getdata())
# 更改所有值为偶数(魔法般的移位)
even_pixels = [(r >> 1 << 1, g >> 1 << 1, b >> 1 << 1) for [r, g, b] in pixels]
# 创建一个相同大小的图片副本
even_image = Image.new(image.mode, image.size)
# 把上面的像素放入到图片副本
even_image.putdata(even_pixels)
return even_image


# 内置函数 bin() 的替代,返回固定长度的二进制字符串
def const_len_bin(arg):
# 去掉 bin() 返回的二进制字符串中的 '0b',并在左边补足 '0' 直到字符串长度为 8
binary = "0" * (8 - (len(bin(arg)) - 2)) + bin(arg).replace('0b', '')
return binary


# 将字符串编码到图片中
def rgba_encode_data_in_image(image, data):
# 获得最低有效位为 0 的图片副本
even_image = rgba_make_image_even(image)
# 将需要被隐藏的字符串转换成二进制字符串
binary = ''.join(map(const_len_bin, bytearray(data, 'utf-8')))
# 如果不可能编码全部数据, 抛出异常
if len(binary) > len(image.getdata()) * 4:
raise Exception(f"Error: Can't encode more than {len(even_image.getdata()) * 4} bits in this image. ")
# 将 binary 中的二进制字符串信息编码进像素里
encoded_pixels = [(r + int(binary[index * 4 + 0]), g + int(binary[index * 4 + 1]), b + int(binary[index * 4 + 2]), t + int(binary[index * 4 + 3])) if index * 4 < len(binary) else (r, g, b, t) for index, (r, g, b, t) in enumerate(list(even_image.getdata()))]
# 创建新图片以存放编码后的像素
encoded_image = Image.new(even_image.mode, even_image.size)
# 添加编码后的数据
encoded_image.putdata(encoded_pixels)
return encoded_image


# 将字符串编码到图片中
def rgb_encode_data_in_image(image, data):
# 获得最低有效位为 0 的图片副本
even_image = rgb_make_image_even(image)
# 将需要被隐藏的字符串转换成二进制字符串
binary = ''.join(map(const_len_bin, bytearray(data, 'utf-8')))
# 将转换的比特流数据末位补零,使其长度为3的倍数,防止其在下面重新编码的过程中发生越界
if len(binary) % 3 != 0:
rema = len(binary) % 3
binary = binary + ('0' * (3 - rema))
# print(len(binary))
# 如果不可能编码全部数据,抛出异常
if len(binary) > len(image.getdata()) * 3:
raise Exception(f"Error: Can't encode more than {len(even_image.getdata()) * 3} bits in this image. ")
# even_imageList = list(even_image.getdata())
# 将 binary 中的二进制字符串信息编码进像素里
encoded_pixels = [(r + int(binary[index * 3 + 0]), g + int(binary[index * 3 + 1]), b + int(binary[index * 3 + 2])) if index * 3 < len(binary) else (r, g, b) for index, (r, g, b) in enumerate(list(even_image.getdata()))]
# 创建新图片以存放编码后的像素
encoded_image = Image.new(even_image.mode, even_image.size)
# 添加编码后的数据
encoded_image.putdata(encoded_pixels)
return encoded_image


# 从二进制字符串转为 UTF-8 字符串
def binary_to_string(binary):
index = 0
string = []
rec = lambda x, i: x[2:8] + (rec(x[8:], i - 1) if i > 1 else '') if x else ''
# rec = lambda x, i: x and (x[2:8] + (i > 1 and rec(x[8:], i-1) or '')) or ''
fun = lambda x, i: x[i + 1:8] + rec(x[8:], i - 1)
while index + 1 < len(binary):
char_type = binary[index:].index('0') # 存放字符所占字节数,一个字节的字符会存为 0
length = char_type * 8 if char_type else 8
string.append(chr(int(fun(binary[index:index + length], char_type), 2)))
index += length
return ''.join(string)


# 解码隐藏数据
def rgba_decode_image(image):
pixels = list(image.getdata()) # 获得像素列表
binary = ''.join([str(int(r >> 1 << 1 != r)) + str(int(g >> 1 << 1 != g)) + str(int(b >> 1 << 1 != b)) + str(int(t >> 1 << 1 != t)) for (r, g, b, t) in pixels]) # 提取图片中所有最低有效位中的数据
# 找到数据截止处的索引
location_double_null = binary.find('0000000000000000')
end_index = location_double_null + (
8 - (location_double_null % 8)) if location_double_null % 8 != 0 else location_double_null
data = binary_to_string(binary[0:end_index])
return data


# 解码隐藏数据
def rgb_decode_image(image):
# 获得像素列表
pixels = list(image.getdata())
# 提取图片中所有最低有效位中的数据
binary = ''.join([str(int(r >> 1 << 1 != r)) + str(int(g >> 1 << 1 != g)) + str(int(b >> 1 << 1 != b)) for (r, g, b) in pixels])
# 找到数据截止处的索引
location_double_null = binary.find('0000000000000000')
end_index = location_double_null + (8 - (location_double_null % 8)) if location_double_null % 8 != 0 else location_double_null
data = binary_to_string(binary[0:end_index])
return data


def is_text_file(path):
if path.endswith(".txt"):
return True
elif path.endswith(".m"):
return True
elif path.endswith(".h"):
return True
elif path.endswith(".c"):
return True
elif path.endswith(".py"):
return True
else:
return False


if __name__ == '__main__':
"""command-line interface"""
arguments = docopt(__doc__)
# print(arguments)

if arguments['-e'] or arguments['encode']:
if arguments['<text>'] is None:
arguments['<text>'] = "待加密的文本"
if arguments['<encoded_image>'] is None:
arguments['<encoded_image>'] = "encoded_image.png"

if is_text_file(arguments['<text>']):
with open(arguments['<text>'], 'rt') as f:
arguments['<text>'] = f.read()

print("载体图片:")
print(arguments['<originImage>'] + "\n")
print("待加密密文:")
print(arguments['<text>'] + "\n")
print("加密后图片:")
print(arguments['<encoded_image>'] + "\n")
print("加密中……\n")
im = Image.open(arguments['<originImage>'])
if im.mode == 'RGBA':
rgba_encode_data_in_image(im, arguments['<text>']).save(arguments['<encoded_image>'])
# elif im.mode == 'RGB':
# rgb_encode_data_in_image(im, arguments['<text>']).save(arguments['<encoded_image>'])
else:
print("暂不支持此图片格式……")

print("加密完成,密文为:\n" + arguments['<text>'] + "\n")
elif arguments['-d'] or arguments['decode']:
print("解密中……\n")
im = Image.open(arguments['<encoded_image>'])
if im.mode == 'RGBA':
print("解秘完成,密文为:\n" + rgba_decode_image(im) + "\n")
# elif im.mode == 'RGB':
# print("解秘完成,密文为:\n"+rgb_decode_image(im)+"\n")
else:
print("非法的图片格式……")

向图片中注入隐写数据

1
python3 main.py -e <file>.png <text>
  • 注入隐写数据完成后会在当前目录下生成文件名为encoded_image.png的新图片

从图片中提取隐写数据

1
python3 main.py -d <file>.png

完成

参考文献

微信公众号——RainTalk