Introduction
A well known method of steganoanalysis is to search one coloured area of the image for variations. In diffuse areas where every pixel has a different color than its neighbors, variations by hidden bits are hard to detect, but most pictures also contain areas with smooth colors. Look at this one:
- The blue sky in the upper middle should not contain hidden data, because there are nearly no natural variations in the colors.
- The clouds have more shades of blue, but anything that's not blue would be easy to find. If any data has to be hidden in the clouds, not more than one bit per pixel should be changed.
- It is the same with the trees on the right: changing the higher bits would produce light colors, but only dark pixels are allowed here, so the capacity of each pixel is reduced to one or two bits.
- The boats and the beach on the left side are better. They contain red, yellow, white, blue, green... We can change up to 7 bits in this region, nobody will notice anything.
To escape from simple variations analysis, we'll hide our secret message only in these regions, and with adjusted "bit rates":
Edit and Store Regions
Just as in the preceding examples, we need a carrier bitmap, a secret message, and a key.
The new feature is a Region Editor which lets the user define regions and their capacities.
An easy way to draw a region is to click the points of a polygon. So, we let the user click on the image, and add every clicked point to a polygon. A polygon can be closed with a double click, then the next click starts a new polygon:
private void picImage_MouseUp(object sender, MouseEventArgs e){
if (e.Button == MouseButtons.Left){
if (isDoubleClicked){
isDoubleClicked = false;
}
else{
if (!isDrawing){
isDrawing = true;
drawingPoints = new ArrayList();
cleanImage = picImage.Image;
bufferImage = new Bitmap(cleanImage.Width, cleanImage.Height);
}
AddPoint(e.X, e.Y);
}
}
}
When a polygon is being closed by a double click, we have to make sure that it does not overlap one of the already existing polygons. If the new polygon intersects another polygon, we merge the two regions. If the p�lygon stands alone, we create a new region and add it to the list. ctlRegions
is a RegionInfoList
, this control displays statistics and input fields for each region.
private void picImage_DoubleClick(object sender, EventArgs e){
if (drawingPoints.Count > 2){
isDrawing = false;
isDoubleClicked = true;
Point[] points = (Point[])drawingPoints.ToArray(typeof(Point));
GraphicsPath path = new GraphicsPath();
path.AddPolygon(points);
if (!UniteWithIntersectedRegions(path, points)){
RegionInfo info = new RegionInfo(path, points, picImage.Image.Size);
drawnRegions.Add(info);
ctlRegions.Add(new RegionInfoListItem(info));
}
ReDrawImages(true);
}
}
If another region has been drawn, we have to update the map and the statistics block. ReDrawImages
paints the regions onto the source image and the map overview. (The map overview and the gradient brush are not necessary, they're just a nice visual effect.)
private void ReDrawImages(bool updateSummary){
Image bufferImageNoBackground =
new Bitmap(baseImage.Width, baseImage.Height);
Image bufferImageWithBackground = new
Bitmap(baseImage.Width, baseImage.Height);
Graphics graphicsWithBackground =
Graphics.FromImage(bufferImageWithBackground);
Graphics graphicsNoBackground =
Graphics.FromImage(bufferImageNoBackground);
graphicsNoBackground.Clear(Color.White);
graphicsWithBackground.DrawImage(baseImage, 0, 0,
baseImage.Width, baseImage.Height);
foreach (RegionInfo info in drawnRegions){
PathGradientBrush brush =
new PathGradientBrush(info.Points, WrapMode.Clamp);
brush.CenterColor = Color.Transparent;
if (info == selectedRegionInfo){
brush.SurroundColors = new Color[1] { Color.Green };
}else{
brush.SurroundColors = new Color[1] { Color.Red };
}
graphicsWithBackground.DrawPolygon(new
Pen(Color.Black, 4), info.Points);
graphicsNoBackground.DrawPolygon(new
Pen(Color.Black, 4), info.Points);
graphicsWithBackground.FillRegion(brush, info.Region);
graphicsNoBackground.FillRegion(brush, info.Region);
}
graphicsWithBackground.Dispose();
graphicsNoBackground.Dispose();
picImage.Image = bufferImageWithBackground;
picMap.Image = bufferImageNoBackground;
picImage.Invalidate();
picMap.Invalidate();
if (updateSummary) { UpdateSummary(); }
}
The map has to be stored in the first pixels of the image so that it can be extracted before the rest of the message. That means, we have to embed a header into the image. When extracting the hidden message, we first have to extract the header, read the region information from it, and then we can extract the actual message from those regions. The header can be spread over all pixels from 0/0 to the first pixel in the topmost region. We won't know where the first region begins before we've extracted the map, so we have to store the index of the first pixel that belongs to any region in the header itself. The coordinates of this pixel are not important, because we'll treat the pixels as one long stream, not as rows and columns. A complete header contains these information:
- (
Int32
) Index (not coordinates!) of the topmost pixel in the first region.
- (
Int32
) Length of the following region data.
- For every region:
- (
Int32
) Length (Region.GetRegionData().Data.Length
)
- (
Int32
) Capacity (Count of bytes to hide in this region)
- (
byte
) Count of used bits per pixel
- (
byte[]
) Region (Region.GetRegionData().Data
)
The length of the header depends on the count and the complexity of the regions. When a new region is added in the Region Editor, we must check the new header's length and the position on the topmost region. If there are not enough pixels left between the image's first pixel and the first region, the header cannot be hidden. In that case, we'll display a warning and disable the "Next" button. The regions that are going to carry the actual message have to be big enough, we'll display another warning if the message does not fit into the regions:
private void UpdateSummary(){
bool isOkay = true;
long countPixels = 0;
int capacity = 0;
RegionInfo firstRegion = null;
int firstPixelInRegions = baseImage.Width * baseImage.Height;
long mapStreamLength = 65;
foreach (RegionInfo info in drawnRegions) {
countPixels += info.CountPixels;
capacity += info.Capacity;
mapStreamLength += 64;
mapStreamLength += info.Region.GetRegionData().Data.Length * 8;
if ((int)info.PixelIndices[0] < firstPixelInRegions) {
firstPixelInRegions = (int)info.PixelIndices[0];
firstRegion = info;
}
}
lblSelectedPixels.Text = countPixels.ToString();
lblPercent.Text = (100 * countPixels /
(baseImage.Width*baseImage.Height)).ToString();
lblCapacity.Text = capacity.ToString();
if (capacity == messageLength) {
SetControlColor(lblCapacity, false);
errors.SetError(lblCapacity, String.Empty);
} else {
SetControlColor(lblCapacity, true);
errors.SetError(lblCapacity,
"Overall capacity must be equal to the message's length.");
isOkay = false;
}
lblHeaderSize.Text = mapStreamLength.ToString() + " Bits";
if (firstRegion != null) {
if (firstPixelInRegions > mapStreamLength) {
lblHeaderSpace.Text = firstPixelInRegions.ToString() + " Pixels";
SetControlColor(lblHeaderSpace, false);
} else {
isOkay = false;
lblHeaderSpace.Text = String.Format(
"{0} Pixels - Please remove the topmost region.",
firstPixelInRegions);
SetControlColor(lblHeaderSpace, true);
selectedRegionInfo = firstRegion;
ctlRegions.SelectItem(firstRegion);
ReDrawImages(false);
}
} else {
lblHeaderSpace.Text = "0 - Please define one or more regions";
SetControlColor(lblHeaderSpace, true);
}
btnNext.Enabled = isOkay;
}
private void SetControlColor(Control control, bool isError) {
if (isError) {
control.BackColor = Color.DarkRed;
control.ForeColor = Color.White;
} else {
control.BackColor = SystemColors.Control;
control.ForeColor = SystemColors.ControlText;
}
}
If the regions are big enough, configured for enough capacity and leaves enough space for the header, UpdateSummary
will enable the "Next" button. Now, the map and the message can be hidden.
Embed the Data
Until now, we have done nothing except receiving input data about the carrier image. Now, the interesting part begins! In the earlier articles, we used the key to locate pixels, and simply embedded the message. This won't work anymore. We have specific regions over which the data has to be distributed, and the header should be distributed evenly over the available pixels at the beginning of the image. That means, the bytes from the key stream cannot be used directly as the next offset, but we can use them to initialize a pseudo-random number generator. This number generator can choose the next offset:
When the message is extracted later on, we just have to initialize the System.Ramdom
object with the same seed (a value from the key stream), and we'll get the same offsets again. But, we need two values to calculate the intervals: the length of the data we want to hide/extract, and the count of the remaining pixels. Let's hide these two Int32
values in the first 64 pixels so that we can read them easily.
public unsafe void Hide(Stream messageStream, Stream keyStream){
Bitmap image = (Bitmap)carrierFile.Image;
image = PaletteToRGB(image);
int pixelOffset = 0, maxOffset = 0, messageValue = 0;
byte key, messageByte, colorComponent;
Random random;
BitmapData bitmapData = image.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
PixelData* pPixel = (PixelData*)bitmapData.Scan0.ToPointer();
PixelData* pFirstPixel;
int firstPixelInRegions = image.Width * image.Height;
foreach (RegionInfo info in carrierFile.RegionInfo){
info.PixelIndices.Sort();
if ((int)info.PixelIndices[0] < firstPixelInRegions){
firstPixelInRegions = (int)info.PixelIndices[0];
}
}
HideInt32(firstPixelInRegions, ref pPixel);
MemoryStream regionData = new MemoryStream();
BinaryWriter regionDataWriter = new BinaryWriter(regionData);
foreach (RegionInfo regionInfo in carrierFile.RegionInfo)
{
byte[] regionBytes = PointsToBytes(regionInfo.Points);
regionDataWriter.Write((Int32)regionBytes.Length);
regionDataWriter.Write((Int32)regionInfo.Capacity);
regionDataWriter.Write(regionInfo.CountUsedBitsPerPixel);
regionDataWriter.Write(regionBytes);
}
regionDataWriter.Flush();
regionData.Seek(0, SeekOrigin.Begin);
HideInt32((Int32)regionData.Length, ref pPixel);
Now that the initial values have been stored, we can distribute the regions map over all the available pixels between pixel 65 and the first region:
pFirstPixel = pPixel;
int regionByte;
while ((regionByte = regionData.ReadByte()) >= 0){
key = GetKey(keyStream);
random = new Random(key);
for (int regionBitIndex = 0; regionBitIndex < 8; ){
pixelOffset += random.Next(1,
(int)((firstPixelInRegions-1 - pixelOffset) /
((regionData.Length - regionData.Position + 1)*8))
);
pPixel = pFirstPixel + pixelOffset;
currentColorComponent = (currentColorComponent == 2) ? 0 :
(currentColorComponent + 1);
colorComponent = GetColorComponent(pPixel, currentColorComponent);
CopyBitsToColor(1, (byte)regionByte,
ref regionBitIndex, ref colorComponent);
SetColorComponent(pPixel, currentColorComponent, colorComponent);
}
}
Now, we have hidden the regions and everything we need to extract them. It is time to get to the point and hide the secret message.
pPixel = (PixelData*)bitmapData.Scan0.ToPointer();
pFirstPixel = pPixel;
foreach (RegionInfo regionInfo in carrierFile.RegionInfo){
pPixel = (PixelData*)bitmapData.Scan0.ToPointer();
pPixel += (int)regionInfo.PixelIndices[0];
pixelOffset = 0;
for (int n = 0; n < regionInfo.Capacity; n++){
messageValue = messageStream.ReadByte();
if (messageValue < 0) { break; }
messageByte = (byte)messageValue;
key = GetKey(keyStream);
random = new Random(key);
for (int messageBitIndex = 0; messageBitIndex < 8; ){
maxOffset = (int)Math.Floor(
((decimal)(regionInfo.CountPixels - pixelOffset - 1) *
regionInfo.CountUsedBitsPerPixel)/
(decimal)((regionInfo.Capacity - n) * 8)
);
pixelOffset += random.Next(1, maxOffset);
pPixel = pFirstPixel + (int)regionInfo.PixelIndices[pixelOffset];
currentColorComponent = (currentColorComponent == 2) ? 0 :
(currentColorComponent + 1);
colorComponent = GetColorComponent(pPixel, currentColorComponent);
CopyBitsToColor(
regionInfo.CountUsedBitsPerPixel,
messageByte, ref messageBitIndex,
ref colorComponent);
SetColorComponent(pPixel, currentColorComponent, colorComponent);
}
}
}
image.UnlockBits(bitmapData);
SaveBitmap(image, carrierFile.DestinationFileName);
}
Extract the Data
So, we have an image, and want to read a hidden message from it. We have to read the message's bytes in the same order they have been hidden:
- Get the length of the map data
- Get the index of the first pixel in the topmost region
- Use these values to extract the regions
- Use the regions to extract the message
Let's go and get the regions!
public unsafe RegionInfo[] ExtractRegionData(Stream keyStream) {
byte key, colorComponent;
PixelData* pPixel;
PixelData* pFirstPixel;
int pixelOffset = 0;
Random random;
Bitmap image = (Bitmap)carrierFile.Image;
BitmapData bitmapData = image.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
pPixel = (PixelData*)bitmapData.Scan0.ToPointer();
int firstPixelInRegions = ExtractInt32(ref pPixel);
int regionDataLength = ExtractInt32(ref pPixel);
pFirstPixel = pPixel;
MemoryStream regionData = new MemoryStream();
byte regionByte;
while (regionDataLength > regionData.Length) {
regionByte = 0;
key = GetKey(keyStream);
random = new Random(key);
for (int regionBitIndex = 0; regionBitIndex < 8; regionBitIndex++) {
pixelOffset += random.Next(1,
(int)(
(firstPixelInRegions - 1 - pixelOffset) /
((regionDataLength - regionData.Length) * 8))
);
pPixel = pFirstPixel + pixelOffset;
currentColorComponent = (currentColorComponent == 2) ? 0 :
(currentColorComponent + 1);
colorComponent = GetColorComponent(pPixel, currentColorComponent);
AddBit(regionBitIndex, ref regionByte, 0, colorComponent);
}
regionData.WriteByte(regionByte);
}
image.UnlockBits(bitmapData);
Now, we have reconstructed the map stream. To do anything useful with it, we have to reconstruct the regions.
ArrayList regions = new ArrayList();
BinaryReader regionReader = new BinaryReader(regionData);
Region anyRegion = new Region();
RegionData anyRegionData = anyRegion.GetRegionData();
Region region;
byte[] regionContent;
int regionLength, regionCapacity;
byte regionBitsPerPixel;
regionReader.BaseStream.Seek(0, SeekOrigin.Begin);
do {
int regionLength = regionReader.ReadInt32();
int regionCapacity = regionReader.ReadInt32();
byte regionBitsPerPixel = regionReader.ReadByte();
byte[] regionContent = regionReader.ReadBytes(regionLength);
Point[] regionPoints = BytesToPoints(regionContent);
GraphicsPath regionPath = new GraphicsPath();
regionPath.AddPolygon(regionPoints);
Region region = new Region(regionPath);
regions.Add(new RegionInfo(region, regionCapacity,
regionBitsPerPixel, image.Size));
} while (regionData.Position < regionData.Length);
return (RegionInfo[])regions.ToArray(typeof(RegionInfo));
}
We're nearly finished. Now, we know in which regions the message is embedded, how many bytes are hidden in which region, and how many bits per pixel must be extracted from the pixels.
public unsafe void Extract(Stream messageStream, Stream keyStream) {
foreach (RegionInfo regionInfo in carrierFile.RegionInfo) {
pFirstPixel = (PixelData*)bitmapData.Scan0.ToPointer();
pPixel = pFirstPixel + (int)regionInfo.PixelIndices[0];
pixelOffset = 0;
for (int n = 0; n < regionInfo.Capacity; n++) {
messageByte = 0;
key = GetKey(keyStream);
random = new Random(key);
for (int messageBitIndex = 0; messageBitIndex < 8; ) {
maxOffset = (int)Math.Floor(
((decimal)(regionInfo.CountPixels - pixelOffset - 1) *
regionInfo.CountUsedBitsPerPixel)/
(decimal)((regionInfo.Capacity - n) * 8)
);
pixelOffset += random.Next(1, maxOffset);
pPixel = pFirstPixel +
(int)regionInfo.PixelIndices[pixelOffset];
currentColorComponent = (currentColorComponent == 2) ? 0 :
(currentColorComponent + 1);
colorComponent = GetColorComponent(pPixel,
currentColorComponent);
for(int carrierBitIndex=0; carrierBitIndex <
regionInfo.CountUsedBitsPerPixel; carrierBitIndex++)
{
AddBit(messageBitIndex, ref messageByte,
carrierBitIndex, colorComponent);
messageBitIndex++;
}
}
messageStream.WriteByte(messageByte);
}
}
}
Done! Now, let's display the message and the regions from which it has been read.
That's all we need to escape from people who try to find our hidden message by searching for unexpected variations in uniform parts of the carrier image.
By the way, there is an additional channel for secret messages: if you're sure that the recipient is creative enough to see it, you can draw outlines and letters with the region editor: