Skip to content

Instantly share code, notes, and snippets.

@mbutler
Last active January 14, 2024 20:22
Show Gist options
  • Save mbutler/d4dd83fbe1bde91925420c2350124460 to your computer and use it in GitHub Desktop.
Save mbutler/d4dd83fbe1bde91925420c2350124460 to your computer and use it in GitHub Desktop.
steganography in base64 images
const PNG = require('pngjs').PNG
const fs = require('fs')
// Function to embed text into a base64 encoded PNG
function embedTextInBase64PNG(base64Image, text) {
let data = Buffer.from(base64Image, 'base64')
let png = PNG.sync.read(data)
let textBinary = (text + '\0').split('').map(char => char.charCodeAt(0).toString(2).padStart(8, '0')).join('')
let dataIndex = 0
for (let i = 0; i < png.data.length && dataIndex < textBinary.length; i += 4) {
for (let bit = 0; bit < 3 && dataIndex < textBinary.length; bit++, dataIndex++) {
png.data[i + bit] = (png.data[i + bit] & 0xFE) | parseInt(textBinary[dataIndex])
}
}
let buffer = PNG.sync.write(png)
return buffer.toString('base64')
}
// Function to extract text from a base64 encoded PNG
function extractTextFromBase64PNG(base64Image) {
let data = Buffer.from(base64Image, 'base64')
let png = PNG.sync.read(data)
let binaryMessage = []
let text = ''
for (let i = 0; i < png.data.length; i += 4) {
for (let bit = 0; bit < 3; bit++) {
binaryMessage.push(png.data[i + bit] & 0x01)
}
}
console.log("Total binary length: " + binaryMessage.length);
for (let i = 0; i < binaryMessage.length; i += 8) {
let byte = binaryMessage.slice(i, i + 8).join('')
let charCode = parseInt(byte, 2)
if (charCode === 0) {
break; // Stop at the null character
}
text += String.fromCharCode(charCode)
}
return text;
}
// Example usage
let originalImageBase64 = fs.readFileSync('input.png', { encoding: 'base64' })
let embeddedImageBase64 = embedTextInBase64PNG(originalImageBase64, 'Hidden message!')
fs.writeFileSync('output.png', embeddedImageBase64, { encoding: 'base64' })
let extractedMessage = extractTextFromBase64PNG(embeddedImageBase64)
console.log('Extracted Message:', extractedMessage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment