【发布时间】:2018-10-02 20:03:27
【问题描述】:
我正在使用 lodePNG 库对 png 图像进行编码,并使用导入的 txt 文件更改像素的 LSB。我已经编译了程序,但我不确定 PNG 文件是否实际上是根据我的按位运算进行编码的。
lodePNG 库从 PNG 图像解码/编码,并将像素存储在矢量“图像”中,每个像素 4 个字节,有序 RGBARGBA...,
void decodeOneStep(const char* filename)
{
unsigned width, height;
//decode
unsigned error = lodepng::decode(image, width, height, filename);
//if there's an error, display it
if (error) std::cout << "decoder error " << error << ": " <<
lodepng_error_text(error) << std::endl;
}
程序采用文本文件和 PNG 文件的命令行参数。我还没有包括参数的错误检查。
int const MAX_SIZE = 100;
std::vector<unsigned char> image;
int main(int argc, char *argv[])
{
const char* filename;
char* textArray = new char[MAX_SIZE];
std::ifstream textfile;
textfile.open(argv[1]);
int numCount = 0;
while (!textfile.eof() && numCount < MAX_SIZE)
{
textfile.get(textArray[numCount]); //reading single character from file to array
numCount++;
}
textfile.close();
filename = argv[2];
decodeOneStep(filename);
unsigned width = 512, height = 512;
image.resize(width * height * 4);
int pixCount = 0;
for (int i = 0; i < numCount - 1; i++) {
std::cout << textArray[i];
for (int j = 0; j < 8; j++) {
std::cout << ((textArray[i]) & 1); //used to see actual bit value.
image[pixCount++] |= ((textArray[i]) & 1);
(textArray[i]) >>= 1;
}
std::cout << std::endl;
}
encodeOneStep(filename, image, width, height);
在 for 循环中,我将遍历向量中的每个像素,并将 LSB 替换为 char 中的位。由于一个 char 是 8 个字节,所以 for 循环循环了 8 次。这个程序应该适用于大多数不超过大小的 PNG 图像和文本,但我不确定按位运算实际上是否在做任何事情。另外,我如何能够移动这些位,以便我们将 char 位从 MSB 存储到 LSB?我觉得我理解像素值(位)如何存储在数组中的方式有问题。
编辑:测试我在新的位操作上运行:
for (int j = 7; j >= 0; j--) {
//These tests were written to see if the 4-bits of the pixels were actually being replaced.
//The LSB of the pixel bits are replaced with the MSB of the text character.
std::cout <<"Initial pixel 4-bits: " << std::bitset <4>(image[pixCount]) << " ";
std::cout << "MSB of char: " << ((textArray[i] >> j) & 0x01) << " ";
std::cout << "Pixel LSB replaced: " << ((image[pixCount] & mask) | ((textArray[i] >> j) & 0x01)) << " ";
image[pixCount] = (image[pixCount] & mask) | ((textArray[i] >> j) & 0x01);
pixCount++;
std::cout << std::endl;
}
测试结果:
For char 'a'
Initial pixel 4-bits : 0000 MSB: 0 Pixel LSB replaced: 0
Initial pixel 4-bits : 0001 MSB: 1 Pixel LSB replaced: 1
Initial pixel 4-bits : 0001 MSB: 1 Pixel LSB replaced: 1
Initial pixel 4-bits : 0000 MSB: 0 Pixel LSB replaced: 0
Initial pixel 4-bits : 0000 MSB: 0 Pixel LSB replaced: 0
Initial pixel 4-bits : 0000 MSB: 0 Pixel LSB replaced: 0
Initial pixel 4-bits : 0000 MSB: 0 Pixel LSB replaced: 0
Initial pixel 4-bits : 0001 MSB: 1 Pixel LSB replaced: 1
【问题讨论】:
-
如果文本包含 1,
image[pixCount++] |= ((textArray[i]) & 1);似乎会添加一点。但如果文本包含 0,您还必须从图像中删除一点。
标签: c++ encryption cryptography bit-manipulation steganography