设为首页 - 加入收藏  
您的当前位置:首页 >应用开发 >如何使用Python实现最低有效位隐写术? 正文

如何使用Python实现最低有效位隐写术?

来源:汇智坊编辑:应用开发时间:2025-11-02 20:50:18

本文转载自公众号“读芯术”(ID:AI_Discovery)

 隐写术是何使一门关于在适当的多媒体载体中传输秘密数据的科学,例如在图像、用P隐写音频和视频文件中。实术它的现最效位假设是,如果特征是何使可见的,那么攻击点就是用P隐写明显的,因此这里的实术目标总是隐藏嵌入数据的存在。

LSB图像隐写术

LSB隐写术是现最效位一种图像隐写术技术,通过用要隐藏的何使信息位替换每个像素的最低有效位,将信息隐藏在图像中。用P隐写为了更好地理解,实术将数字图像视为2D像素阵列,现最效位每个像素包含的何使值取决于其类型和深度。

我们将考虑最广泛使用的用P隐写模式——RGB(3×8位像素,真彩)和RGBA(4x8位像素,实术带透明遮罩的真彩),服务器租用这些值的范围从0到255(8位值)。

将图像表示为2D阵列的RGB像素

通过使用ASCII表,可以将消息转换为十进制值,然后转换为二进制值,接着逐个迭代像素值,在将像素值转换为二进制后,将每个最低有效位替换为序列中的该消息位。

要解码一个已编码的图像,只需颠倒这个过程:收集并存储每个像素的最后一位,将它们分成8个一组,并将其转换回ASCII字符,以得到隐藏的信息。

PYTHON操作

试着使用Python库PIL和NumPY来逐步实现上述概念。

步骤1:导入所有必需的python库 import numpy as np from PIL import Image  步骤2:启用编码器功能

首先,编写代码,将源图像转换成一个NumPy像素阵列,并存储图像的大小。检查图像的模式是RGB还是RGBA,然后设置n的值。还需计算像素的总数。b2b信息网

def Encode(src, message, dest):     img = Image.open(src, r)     width, height = img.size    array = np.array(list(img.getdata()))     if img.mode == RGB:         n = 3         m = 0     elif img.mode == RGBA:         n = 4         m = 1     total_pixels = array.size//n 

其次,在秘密消息的末尾添加一个分隔符(“$T3G0”),这样程序在解码时就知道什么时候该停止,将这个更新后的消息转换成二进制形式,并计算出所需的像素。

message += "$t3g0" b_message = .join([format(ord(i), "08b") for i in message]) req_pixels = len(b_message) 

接着,检查可用的总像素是否足够用于秘密消息。如果继续逐个迭代像素,并将它们的最低有效位修改为秘密消息的位,直到包括分隔符的完整消息已经被隐藏。

if req_pixels > total_pixels:     print("ERROR: Need larger filesize")else:    index=0    for p in range(total_pixels):         for q in range(m, n):             if index < req_pixels:                 array[p][q] =int(bin(array[p][q])[2:9] + b_message[index], 2)                 index += 1 

最后,有了更新后的像素数组,可以使用它来创建并保存为目标输出图像。

array=array.reshape(height, width, n) enc_img = Image.fromarray(array.astype(uint8), img.mode) enc_img.save(dest)print("Image Encoded Successfully") 

这样,编码器功能就完成了,是这样的:

def Encode(src, message, dest):     img = Image.open(src, r)    width, height = img.size    array = np.array(list(img.getdata()))    if img.mode == RGB:        n = 3        m = 0    elif img.mode == RGBA:        n = 4        m = 1    total_pixels = array.size//n     message += "$t3g0"     b_message = .join([format(ord(i),"08b") for i in message])     req_pixels = len(b_message)     if req_pixels > total_pixels:         print("ERROR: Need largerfile size")    else:        index=0        for p in range(total_pixels):             for q in range(m, n):                 if index < req_pixels:                     array[p][q] =int(bin(array[p][q])[2:9] + b_message[index], 2)                     index += 1         array=array.reshape(height,width, n)         enc_img =Image.fromarray(array.astype(uint8), img.mode)         enc_img.save(dest)        print("Image EncodedSuccessfully")  步骤3:启用解码器功能

首先,重复类似的步骤,将源图像的像素保存为一个数组,计算模式,并计算总像素。IT技术网

def Decode(src):     img = Image.open(src, r)     array = np.array(list(img.getdata()))     if img.mode == RGB:         n = 3         m = 0     elif img.mode == RGBA:         n = 4         m = 1     total_pixels = array.size//n 

其次,需要从图像左上角开始的每个像素中提取最低有效位,并以8个为一组存储。接下来,将这些组转换成ASCII字符来查找隐藏的消息,直到完全读取之前插入的分隔符。

hidden_bits = "" for p in range(total_pixels):     for q in range(m, n):         hidden_bits +=(bin(array[p][q])[2:][-1]) hidden_bits = [hidden_bits[i:i+8] for i in range(0, len(hidden_bits), 8)] message = "" for i in range(len(hidden_bits)):     if message[-5:] == "$t3g0":         break     else:         message +=chr(int(hidden_bits[i], 2)) 

最后,检查是否找到了分隔符。如果没有,意味着图像中没有隐藏的信息。

if "$t3g0" in message:     print("Hidden Message:",message[:-5]) else:     print("No Hidden MessageFound") 

这样,我们的解码器功能就完成了,看起来应该是这样的:

def Decode(src):     img = Image.open(src, r)    array = np.array(list(img.getdata()))    if img.mode == RGB:        n = 3        m = 0    elif img.mode == RGBA:        n = 4        m = 1    total_pixels = array.size//n     hidden_bits = ""     for p in range(total_pixels):         for q in range(m, n):             hidden_bits +=(bin(array[p][q])[2:][-1])     hidden_bits = [hidden_bits[i:i+8] fori in range(0, len(hidden_bits), 8)]     message = ""     for i in range(len(hidden_bits)):         if message[-5:] =="$t3g0":            break        else:            message +=chr(int(hidden_bits[i], 2))    if "$t3g0" in message:        print("Hidden Message:",message[:-5])    else:        print("No Hidden MessageFound")  步骤4:制作主要功能

对于主要功能,我们需询问用户想要执行哪个功能——编码还是解码。

若是编码,则要求用户输入以下内容——带扩展名的源图像名称、秘密消息和带扩展名的目标图像名称。若是解码,则要求用户提供隐藏了消息的源图像。

def Stego():     print("--Welcome to$t3g0--")     print("1: Encode")     print("2: Decode")     func = input()     if func == 1:         print("Enter Source ImagePath")         src = input()         print("Enter Message toHide")         message = input()         print("Enter Destination ImagePath")         dest = input()         print("Encoding...")         Encode(src, message, dest)    elif func == 2:         print("Enter Source ImagePath")         src = input()         print("Decoding...")         Decode(src)    else:         print("ERROR: Invalid optionchosen")  步骤5:把以上所有功能放在一起,我们的LSB图像隐写程序就准备好了。

请注意,在一项研究中,观察到传统的LSB在JPEG的情况下是无效的,因为数据会因为其有损性质而在压缩时被操纵。而对于PNG图像,简单的LSB是适用的,在压缩时不会有任何数据损失。因此,最好只在PNG图像上运行你的程序。

举例

1.编码信息

2.解码信息

0.1258s , 11715.4609375 kb

Copyright © 2025 Powered by 如何使用Python实现最低有效位隐写术?,汇智坊  滇ICP备2023006006号-2

sitemap

Top