Of course. Hiding a file within a JPEG without damaging the visible image is a classic steganography problem. The key is to understand the JPEG file format and find a place to insert data that image viewers will ignore.
The Method: Using the JPEG Comment Marker
The JPEG file format is not just a raw block of pixel data. It's a structured format with "markers" that define different segments (like header information, quantization tables, and the actual compressed image data).
The most reliable and standard-compliant way to hide data without corrupting the image is to use the Comment (COM) marker, which is 0xFFFE. Any data placed within a COM segment is ignored by image decoders, so the image will render perfectly.
Our program will create a custom COM segment containing:
- A unique "magic number" to identify our hidden data.
- The original filename of the hidden file.
- The size of the hidden file.
- The actual content of the hidden file.
We will insert this entire block just before the End of Image (EOI) marker (0xFFD9), which is always at the very end of the JPEG data stream.
C++ Code
Here is a complete C++ program that can both hide and extract files. It's written to be portable and safe, handling file I/O carefully.
steganography.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdint> // For uint64_t, uint8_t
#include <stdexcept> // For std::runtime_error
// A unique sequence of bytes to identify our hidden data block
const std::vector<char> MAGIC_BYTES = {'S', 'T', 'G', 'H', 'D', 'R'};
// --- Hiding Functionality ---
void hideFile(const std::string& jpegPath, const std::string& fileToHidePath, const std::string& outputPath) {
// 1. Read the source JPEG image
std::ifstream jpegFile(jpegPath, std::ios::binary);
if (!jpegFile.is_open()) {
throw std::runtime_error("Could not open source JPEG file: " + jpegPath);
}
std::vector<char> jpegData((std::istreambuf_iterator<char>(jpegFile)), std::istreambuf_iterator<char>());
jpegFile.close();
// 2. Find the End of Image (EOI) marker (0xFFD9)
// We search from the end for efficiency.
size_t eoiPosition = std::string::npos;
for (size_t i = jpegData.size() - 2; i > 0; --i) {
if (static_cast<unsigned char>(jpegData[i]) == 0xFF && static_cast<unsigned char>(jpegData[i + 1]) == 0xD9) {
eoiPosition = i;
break;
}
}
if (eoiPosition == std::string::npos) {
throw std::runtime_error("Could not find EOI marker in JPEG file.");
}
// 3. Read the file to be hidden
std::ifstream fileToHide(fileToHidePath, std::ios::binary);
if (!fileToHide.is_open()) {
throw std::runtime_error("Could not open file to hide: " + fileToHidePath);
}
std::vector<char> hideData((std::istreambuf_iterator<char>(fileToHide)), std::istreambuf_iterator<char>());
fileToHide.close();
// 4. Create the payload
std::vector<char> payload;
// Get just the filename from the path
std::string filename = fileToHidePath.substr(fileToHidePath.find_last_of("/\\") + 1);
if (filename.length() > 255) {
throw std::runtime_error("Filename is too long (max 255 characters).");
}
// a. Filename length (1 byte)
uint8_t filenameLen = static_cast<uint8_t>(filename.length());
payload.push_back(static_cast<char>(filenameLen));
// b. Filename
payload.insert(payload.end(), filename.begin(), filename.end());
// c. File data size (8 bytes, big-endian for portability)
uint64_t dataSize = hideData.size();
for (int i = 7; i >= 0; --i) {
payload.push_back(static_cast<char>((dataSize >> (i * 8)) & 0xFF));
}
// d. File data
payload.insert(payload.end(), hideData.begin(), hideData.end());
// 5. Create the complete COM segment
std::vector<char> comSegment;
// a. COM marker
comSegment.push_back(static_cast<char>(0xFF));
comSegment.push_back(static_cast<char>(0xFE));
// b. Segment length (2 bytes, big-endian), including the length bytes themselves
// Length = magic_bytes + payload
uint16_t segmentLen = static_cast<uint16_t>(2 + MAGIC_BYTES.size() + payload.size());
comSegment.push_back(static_cast<char>((segmentLen >> 8) & 0xFF));
comSegment.push_back(static_cast<char>(segmentLen & 0xFF));
// c. Our magic identifier
comSegment.insert(comSegment.end(), MAGIC_BYTES.begin(), MAGIC_BYTES.end());
// d. The actual payload
comSegment.insert(comSegment.end(), payload.begin(), payload.end());
// 6. Write the new JPEG file
std::ofstream outputFile(outputPath, std::ios::binary);
if (!outputFile.is_open()) {
throw std::runtime_error("Could not create output file: " + outputPath);
}
// Write original JPEG data up to the EOI marker
outputFile.write(jpegData.data(), eoiPosition);
// Write our new COM segment
outputFile.write(comSegment.data(), comSegment.size());
// Write the EOI marker
outputFile.write(jpegData.data() + eoiPosition, jpegData.size() - eoiPosition);
outputFile.close();
std::cout << "Successfully hid '" << fileToHidePath << "' in '" << outputPath << "'." << std::endl;
}
// --- Extraction Functionality ---
void extractFile(const std::string& jpegPath) {
// 1. Read the steganographic JPEG image
std::ifstream jpegFile(jpegPath, std::ios::binary);
if (!jpegFile.is_open()) {
throw std::runtime_error("Could not open source JPEG file: " + jpegPath);
}
std::vector<char> jpegData((std::istreambuf_iterator<char>(jpegFile)), std::istreambuf_iterator<char>());
jpegFile.close();
// 2. Search for our COM segment with the magic bytes
auto it = std::search(jpegData.begin(), jpegData.end(), MAGIC_BYTES.begin(), MAGIC_BYTES.end());
if (it == jpegData.end()) {
throw std::runtime_error("No hidden file with the correct magic header found.");
}
// 3. Parse the metadata and data
size_t offset = std::distance(jpegData.begin(), it) + MAGIC_BYTES.size();
// a. Filename length
uint8_t filenameLen = static_cast<uint8_t>(jpegData[offset]);
offset += 1;
// b. Filename
std::string filename(jpegData.begin() + offset, jpegData.begin() + offset + filenameLen);
offset += filenameLen;
// c. File data size
uint64_t dataSize = 0;
for (int i = 0; i < 8; ++i) {
dataSize = (dataSize << 8) | static_cast<uint8_t>(jpegData[offset + i]);
}
offset += 8;
// d. File data
std::vector<char> fileData(jpegData.begin() + offset, jpegData.begin() + offset + dataSize);
// 4. Write the extracted file
std::ofstream outputFile(filename, std::ios::binary);
if (!outputFile.is_open()) {
throw std::runtime_error("Could not create extracted file: " + filename);
}
outputFile.write(fileData.data(), fileData.size());
outputFile.close();
std::cout << "Successfully extracted file to '" << filename << "' (" << dataSize << " bytes)." << std::endl;
}
void printUsage() {
std::cerr << "Usage:\n"
<< " To hide a file: stego hide <source_image.jpg> <file_to_hide> <output_image.jpg>\n"
<< " To extract a file: stego extract <stego_image.jpg>\n";
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printUsage();
return 1;
}
std::string mode = argv[1];
try {
if (mode == "hide" && argc == 5) {
hideFile(argv[2], argv[3], argv[4]);
} else if (mode == "extract" && argc == 3) {
extractFile(argv[2]);
} else {
printUsage();
return 1;
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
How to Compile and Use
-
Save: Save the code above as steganography.cpp.
-
Compile: You'll need a C++ compiler like G++ (which comes with MinGW on Windows or is standard on Linux). Open a terminal or command prompt.
g++ -std=c++17 -O2 steganography.cpp -o stego
-std=c++17: We use modern C++ features.
-O2: A standard optimization flag.
-o stego: Names the output executable stego (or stego.exe on Windows).
-
Use:
Let's say you have an image source.jpg and a text file secret.txt.
-
To Hide the file:
./stego hide source.jpg secret.txt output.jpg
This will create a new file, output.jpg. If you open output.jpg in an image viewer, it will look identical to source.jpg.
-
To Extract the file:
./stego extract output.jpg
This will read output.jpg, find the hidden data, and recreate the secret.txt file in the same directory.
Limitations and Potential Improvements
- No Encryption: This code provides obscurity, not security. Anyone with this program (or knowledge of the JPEG format) can extract the file. For real security, you should encrypt the file before hiding it.
- Metadata is Detectable: The presence of a large, non-standard COM segment is a tell-tale sign of steganography. Sophisticated analysis can easily flag this file as suspicious.
- File Size: Reading entire files into
std::vector is simple but can consume a lot of RAM for very large images or hidden files. A more advanced version would use a streaming approach, reading and writing in smaller chunks.
- Single File: This implementation hides only one file. It could be extended to bundle multiple files (perhaps by creating a tar or zip archive first and hiding that single archive file).