> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-6/steganography/trick-0201.md).

# Image Header Manipulation (PNG to JPG)

***

File headers often contain magic bytes that identify the file type. If these bytes are incorrect (e.g., a JPG file has a PNG header), the file may not open correctly, even with the right extension. For instance, a PNG file typically starts with the hexadecimal bytes `89 50 4E 47 0D 0A 1A 0A`, while a JPEG (JFIF) file commonly starts with `FF D8 FF E0`. An "Invalid image file header" error often indicates this mismatch.

Use a hex editor to inspect the beginning of the file. Popular hex editors include `hexedit`, `bless`, `ghex`, `okteta` on Linux, or HxD and Hex Editor Neo on Windows. Identify the incorrect header bytes and replace them with the correct magic bytes for the expected file type.

For example, if a file named `thm.jpg` shows a PNG header (like `¢PNG` or `89 50 4E 47` in hex) but is expected to be a JPG, replace the initial bytes with the standard JPG header bytes (`FF D8 FF E0 00 10 4A 46 49 46`).

```bash
hexeditor thm.jpg
```

Navigate to the beginning of the file and manually change the first 10 bytes to `FF D8 FF E0 00 10 4A 46 49 46`. Save the changes.

Alternatively, you can modify file headers directly from the command line without an interactive editor. For command-line modification, tools like `printf` and `dd` can be combined. Use `printf` with hex escape sequences (`\xNN`) to generate the binary representation of the desired magic bytes. Pipe this output to `dd`, specifying the target file (`of=`), a block size of 1 byte (`bs=1`), the number of bytes to write (`count=10`), and crucially, `conv=notrunc` to ensure only the beginning of the file is overwritten and the rest remains intact. The `conv=notrunc` option prevents `dd` from truncating the output file after writing the specified count of bytes, which is essential when only modifying the header.

```bash
# Assuming you have the correct hex bytes FF D8 FF E0 00 10 4A 46 49 46
# You can use printf to generate the binary header and dd to write it.
printf '\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46' | dd of=thm.jpg bs=1 count=10 conv=notrunc
```

To change a PNG header back to the standard PNG header bytes (`89 50 4E 47 0D 0A 1A 0A`), you would use the corresponding hex escape sequences with `printf`:

```bash
# Example to change header to PNG
printf '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' | dd of=file.png bs=1 count=8 conv=notrunc
```

This command overwrites the first 8 bytes of `file.png` with the standard PNG signature. The `dd` command is capable of overwriting specific parts of a file, making it suitable for patching binary data like file headers.
