首页 > 解决方案 > 如何在一张图像中隐藏两种不同格式的消息并在解码后以相同格式检索?

问题描述

如何隐藏具有两种不同格式的消息,例如int同时隐藏string在图像中并解密相同格式的消息?

                                                             
from stegano import lsb
a = 12345678
b = 'sdghgnh'
c = (a, b)
secret = lsb.hide("images/2.png",str(c))
secret = secret.save("new.png")
clear_message = lsb.reveal(secret)
print(clear_message)


在上面的代码中:a是一个整数并且b是一个字符串数据类型。我需要将它们隐藏在2.png图像文件中并返回一个名为new.png. 如何以相同格式解码图像中的消息?

解码时出现以下错误:

raceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/PIL/Image.py", line 2770, in open
    fp.seek(0)
AttributeError: 'NoneType' object has no attribute 'seek'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rashik/Desktop/fyp/abc.py", line 7, in <module>
    clear_message = lsb.reveal(secret)
  File "/usr/local/lib/python3.9/dist-packages/stegano/lsb/lsb.py", line 103, in reveal
    img = tools.open_image(input_image)
  File "/usr/local/lib/python3.9/dist-packages/stegano/tools.py", line 120, in open_image
    return Image.open(fname_or_instance)
  File "/usr/local/lib/python3.9/dist-packages/PIL/Image.py", line 2772, in open
    fp = io.BytesIO(fp.read())
AttributeError: 'NoneType' object has no attribute 'read'
                                                           

请帮我解码我的消息。

标签: pythonpython-3.xsteganography

解决方案


我认为你在这两行都有错误:

secret = secret.save("new.png")
clear_message = lsb.reveal(secret)

stegano库文档中的示例来看,您应该这样做:

secret.save("new.png")   # this doesn't return anything, so don't reassign secret
clear_message = lsb.reveal("new.png")   # this function expects a filename

这应该可以处理您的隐写术问题,唯一剩下的挑战是将您的 2 元组的字符串表示形式重新转换为两个单独的对象。在这种情况下,该ast.literal_eval函数可能是将字符串表示形式转换回 Python 对象的好方法。

import ast  # this should be a the top of the file, with your other imports

new_c = ast.literal_eval(clear_message)  # parse the string into a tuple
new_a, new_b = new_c                     # unpack the tuple

请注意,ast.literal_eval只能解析最简单类型的对象,即在 Python 代码中具有文字形式的对象(元组、列表、字典、数字、字符串等)。如果您需要对其他更复杂的内容进行编码,则需要编写自己的逻辑来处理其序列化和反序列化(隐写术使用中间的序列化字符串)。


推荐阅读