2

I am trying to hide a string of text into a bitmap using the LSB algorithm, which is replacing the least significant bit of the RGB Values for each pixel. So far I have loped through the pixels of the image and cleared the LSB value for each pixel. The part that I am struggling with is inserting the new LSB values that come from a string.

This is what I have done so far any pointers of where to go next would be helpful

string text = txtEncrypt.Text;
//Gets the ascii value of each character from the string
var n = ASCIIEncoding.ASCII.GetBytes(text);

Bitmap myBitmap = new Bitmap(myPictureBox.Image);
byte[] rgbBytes = new byte[0];
int R=0, G=0, B=0;
for (int i = 0; i < myBitmap.Width; i++)
{
    for (int j = 0; j < myBitmap.Height; j++)
    {
        Color pixel = myBitmap.GetPixel(i, j);

        // now, clear the least significant bit (LSB) from each pixel element
        //Therefore Three bits in each pixel spare

        R = pixel.R - pixel.R % 2;
        G = pixel.G - pixel.G % 2;
        B = pixel.B - pixel.B % 2;

        // Need to insert new values
    }
}
Jonas W
  • 3,200
  • 1
  • 31
  • 44

2 Answers2

1

Although you can do bit manipulation using "regular" arithmetics (the kind they teach in the first grade) it is more common to use bit manipulation operators to achieve the same goal.

For example, writing R = pixel.R & ~1 is a lot more common than subtracting pixel.R % 2.

You don't need to clear the bit before setting it. To force a bit into 1 use R = pixel.R | 1. To force it into zero use the R = pixel.R & ~1 mentioned above.

To iterate bits of the "messagestored as a sequence ofN` bytes use this check:

if (message[pos / 8] & (1 << pos % 8) != 0) {
    // bit at position pos is 1
} else {
    // bit at position pos is 0
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Bitwise operators make this easy to do:

set last bit to 1:

var newR = pixel.R | 0b00000001

set last bit to 0

var newR = pixel.R & 0b11111110

how this works: | merges bits like an or operator would per byte. and & merges bits like an and operator would (psuedocode):

10101000 | 0000001 = 10101001
10101001 & 1111110 = 10101000
Joel Harkes
  • 10,975
  • 3
  • 46
  • 65
  • Although this is deceptively legal C#, it will not do what you want it to do. From C# 7 onwards, binary literals are supported with the `0b` prefix, so `0b11111110` is 254. In all versions of C#, `11111110` is 11 million 111 thousand 110, and `10101001 & 1111110` is `1056768`. – Jeroen Mostert Feb 08 '18 at 12:14
  • @JeroenMostert a yes, i just wrote pseudo code, thanks for the headsup to not confuse anyone i updated the code. – Joel Harkes Feb 08 '18 at 12:17