Skip to content

Instantly share code, notes, and snippets.

@yoavst
Created September 19, 2016 11:51
Show Gist options
  • Save yoavst/7d668f8eeec9bfe9bfea57d83bb9e54e to your computer and use it in GitHub Desktop.
Save yoavst/7d668f8eeec9bfe9bfea57d83bb9e54e to your computer and use it in GitHub Desktop.
BMPHider
package com.yoavst.hacking;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class BMPHider {
private static byte[] toBitArray(byte[] arr) {
byte[] bitArray = new byte[arr.length * 8];
for (int i = 0; i < arr.length; i++) {
byte b = arr[i];
for (int p = 0; p < 8; p++) {
bitArray[i * 8 + p] = (byte) (getBit(b, p));
}
}
return bitArray;
}
private static byte[] toByteArray(byte[] arr) {
byte[] byteArray = new byte[arr.length / 8];
try {
for (int i = 0; i < arr.length; i++) {
byte b = 0;
for (int p = 0; p < 8; p++) {
b = setBit(b, p, arr[i*8+p]);
}
byteArray[i] = b;
}
} catch (ArrayIndexOutOfBoundsException ignored) {}
return byteArray;
}
static void hideIn(File input, File output, String text) {
try {
BufferedImage img = ImageIO.read(input);
byte[] data = toBitArray(text.getBytes(Charset.forName("ascii")));
int p = 0;
loop:
for (int w = 0; w < img.getWidth(); w++) {
for (int h = 0; h < img.getHeight(); h++) {
if (p >= data.length) {
break loop;
}
int realRGB = img.getRGB(w, h);
byte b = data[p];
if (b == 1) {
realRGB |= 1;
} else {
realRGB &= ~0b1;
}
img.setRGB(w, h, realRGB);
p++;
}
}
ImageIO.write(img, "bmp", output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String getHidden(File output) {
try {
BufferedImage img = ImageIO.read(output);
List<Byte> bitArray = new ArrayList<>();
for (int w = 0; w < img.getWidth(); w++) {
for (int h = 0; h < img.getHeight(); h++) {
int pixel = img.getRGB(w, h);
byte value = (byte) (pixel & 1);
bitArray.add(value);
}
}
return new String(toByteArray(to(bitArray)), Charset.forName("ascii"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static byte[] to(List<Byte> byteList) {
byte[] byteArray = new byte[byteList.size()];
for (int index = 0; index < byteList.size(); index++) {
byteArray[index] = byteList.get(index);
}
return byteArray;
}
private static int getBit(byte b, int position) {
return ((b >> position) & 1);
}
private static byte setBit(byte b, int pos, int value) {
if (value == 1) {
return (byte) (b | (1 << pos));
} else {
return (byte) (b & ~(1 << pos));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment