Image Steganography — PHP source
Hide a secret message inside a PNG image or extract a hidden message from one. Uses least-significant-bit encoding with optional AES encryption.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* steganography — least-significant-bit (LSB) hiding on RGBA pixel data,
* with optional AES-256-GCM encryption.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `steganography` tool, ported from
* src/lib/steganography.ts (the canonical TypeScript implementation).
*
* Why this file exists: PHP ships the whole crypto stack in the standard
* library — hash_pbkdf2 for the key stretch and openssl_encrypt/decrypt in
* aes-256-gcm mode (bundled OpenSSL build) for the body — so the WebCrypto
* calls translate one-to-one. The pixel math is pure byte logic: pixels are
* a flat RGBA byte buffer (binary String); the caller supplies it, e.g. from
* imagesetpixel loops or a decoded image.
*
* Wire format (the "payload" hidden in the pixels):
* 4-byte big-endian header, then the body. The header's top bit is an
* encryption flag (1 = body is salt+IV+AES-GCM ciphertext, 0 = body is raw
* UTF-8); the low 31 bits are the body length in bytes. The flag makes the
* "password required" / "not password-protected" errors deterministic.
*
* Payload bits are written MSB-first, one per R/G/B channel in raster order
* (Alpha is never touched): bit i lands in pixel floor(i/3), channel i%3.
* Capacity = floor(width * height * 3 / 8) payload bytes.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
const STEGO_PBKDF2_ITERATIONS = 100000;
const STEGO_SALT_BYTES = 16;
const STEGO_IV_BYTES = 12;
const STEGO_GCM_TAG_BYTES = 16;
/** Salt + IV + GCM tag overhead added to the body when a password is used. */
const STEGO_ENCRYPTION_OVERHEAD_BYTES = STEGO_SALT_BYTES + STEGO_IV_BYTES + STEGO_GCM_TAG_BYTES;
/** The 4-byte length header is also stored in the pixels, so it consumes capacity. */
const STEGO_HEADER_BYTES = 4;
/** PBKDF2-SHA256 (100k iterations) -> 32-byte AES-256-GCM key. */
function stego_derive_key(string $password, string $salt): string
{
return hash_pbkdf2('sha256', $password, $salt, STEGO_PBKDF2_ITERATIONS, 32, true);
}
/**
* AES-256-GCM encrypt bytes -> packed salt + IV + ciphertext (+ tag).
*
* A fresh random salt + IV make every call unique.
*
* @throws RuntimeException when OpenSSL rejects the parameters.
*/
function stego_encrypt_bytes(string $plain, string $password): string
{
$salt = random_bytes(STEGO_SALT_BYTES);
$iv = random_bytes(STEGO_IV_BYTES);
$key = stego_derive_key($password, $salt);
$ciphertext = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed');
}
return $salt . $iv . $ciphertext . $tag;
}
/**
* Unpack and AES-256-GCM decrypt a salt + IV + ciphertext payload.
* GCM authenticates on decrypt, so a wrong password or tampered bytes fail.
*
* @throws RuntimeException on authentication failure.
*/
function stego_decrypt_bytes(string $packed, string $password): string
{
$salt = substr($packed, 0, STEGO_SALT_BYTES);
$iv = substr($packed, STEGO_SALT_BYTES, STEGO_IV_BYTES);
$body = substr($packed, STEGO_SALT_BYTES + STEGO_IV_BYTES);
$data = substr($body, 0, -STEGO_GCM_TAG_BYTES);
$tag = substr($body, -STEGO_GCM_TAG_BYTES);
$key = stego_derive_key($password, $salt);
$plain = openssl_decrypt($data, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false) {
throw new RuntimeException('Decryption failed - wrong password or corrupted data');
}
return $plain;
}
/**
* Max payload bytes (header + body) an image of this size can carry.
*
* @throws InvalidArgumentException for non-positive or non-integer sizes.
*/
function calculate_capacity($width, $height): int
{
if (!is_int($width) || !is_int($height) || $width <= 0 || $height <= 0) {
throw new InvalidArgumentException('Width and height must be positive integers');
}
return intdiv($width * $height * 3, 8);
}
/**
* Write $payload into the LSBs of the R/G/B channels; returns copied pixels
* (the input is never mutated).
*/
function stego_embed_bits(string $data, string $payload): string
{
$out = $data; // PHP strings are value-copied, so the input stays intact
$totalBits = strlen($payload) * 8;
for ($i = 0; $i < $totalBits; $i++) {
$bit = (ord($payload[$i >> 3]) >> (7 - ($i & 7))) & 1;
$idx = intdiv($i, 3) * 4 + ($i % 3);
$out[$idx] = chr((ord($out[$idx]) & 0xfe) | $bit);
}
return $out;
}
/** Read $count payload bytes back out of the R/G/B LSBs. */
function stego_extract_bits(string $data, int $offsetBytes, int $count): string
{
$out = str_repeat("\x00", $count);
$startBit = $offsetBytes * 8;
for ($i = 0; $i < $count * 8; $i++) {
$bitIndex = $startBit + $i;
$bit = ord($data[intdiv($bitIndex, 3) * 4 + ($bitIndex % 3)]) & 1;
$out[$i >> 3] = chr(ord($out[$i >> 3]) | ($bit << (7 - ($i & 7))));
}
return $out;
}
/**
* Hide $message inside a copy of the image's pixels (LSB of R/G/B) and
* return the modified image array ({ width, height, data }). With
* $password, the message body is AES-256-GCM encrypted first. Throws if the
* message (including header and encryption overhead) exceeds the image
* capacity, or on an empty password.
*
* @throws InvalidArgumentException on an empty password or oversize message.
*/
function hide_message(array $image, string $message, ?string $password = null): array
{
if ($password !== null && $password === '') {
throw new InvalidArgumentException('Password must not be empty');
}
$capacity = calculate_capacity($image['width'], $image['height']);
$body = $password !== null ? stego_encrypt_bytes($message, $password) : $message;
$header = strlen($body) | ($password !== null ? 0x80000000 : 0);
$payload = pack('N', $header) . $body; // big-endian length header
if (strlen($payload) > $capacity) {
$maxBody = $capacity - STEGO_HEADER_BYTES;
throw new InvalidArgumentException(sprintf(
'Message too long: %d bytes with overhead, but this image can hold at most %d bytes of message',
strlen($body),
$maxBody
));
}
return ['width' => $image['width'], 'height' => $image['height'],
'data' => stego_embed_bits($image['data'], $payload)];
}
/**
* Read the hidden message out of the image's pixels. Throws when the pixels
* carry no valid payload ("No hidden message found"), when the payload is
* encrypted but no password is given, when a password is given but the
* payload is plaintext, and on a wrong password (GCM failure).
*
* @throws InvalidArgumentException on any of the conditions above.
*/
function extract_message(array $image, ?string $password = null): string
{
if ($password !== null && $password === '') {
throw new InvalidArgumentException('Password must not be empty');
}
$capacity = calculate_capacity($image['width'], $image['height']);
$header = unpack('N', stego_extract_bits($image['data'], 0, STEGO_HEADER_BYTES))[1];
$encrypted = ($header & 0x80000000) !== 0;
$length = $header & 0x7fffffff;
if ($length === 0 && !$encrypted) {
return '';
}
if (STEGO_HEADER_BYTES + $length > $capacity
|| $length < ($encrypted ? STEGO_ENCRYPTION_OVERHEAD_BYTES : 1)) {
throw new InvalidArgumentException('No hidden message found in this image');
}
$body = stego_extract_bits($image['data'], STEGO_HEADER_BYTES, $length);
if (!$encrypted) {
if ($password !== null) {
throw new InvalidArgumentException(
'This message is not password-protected - extract without a password');
}
$text = $body; // PHP strings are raw bytes; a UTF-8 payload stays UTF-8
if (!preg_match('//u', $text)) {
throw new InvalidArgumentException('No hidden message found in this image');
}
return $text;
}
if ($password === null) {
throw new InvalidArgumentException(
'This image contains an encrypted message - a password is required');
}
return stego_decrypt_bytes($body, $password);
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →