file-encryption
A simple file encryption tool using memory-mapped I/O and XOR operation.
Description
file-encryption
modifies a binary file in-place by applying a bitwise XOR
operation using a user-provided numeric key. It efficiently processes large
files in memory page-sized blocks using mmap
, avoiding explicit read/write
loops.
This method can be used for lightweight encryption and decryption, as XOR is symmetric: applying the same key twice restores the original file.
Features
- Fast in-place encryption using memory mapping (
mmap
) - Page-aligned memory processing for better performance
- Supports partial blocks at the end of the file (byte-accurate)
- Symmetric encryption: same operation encrypts and decrypts
- No third-party dependencies, written in pure C
Usage
git clone https://git.scratko.xyz/file-encryption
cd file-encryption
gcc -Wall encryption.c -o encryption
./encryption <filename> <key>
<filename>
— path to the target file
<key>
— numeric key used for encryption (unsigned integer)
Example
./encryption secret.bin 12345
This will XOR every 4-byte word of secret.bin
with 12345
. Running the same
command again will restore the original content.
How it works
- The file is opened with
O_RDWR
and memory-mapped usingmmap()
. - The numeric key is bitwise-inverted:
~key
. - The file is processed block-by-block in chunks of
4096
bytes (aligned to system page size). - For each 4-byte block in the mapped memory, a XOR with the key is applied.
- If the file ends with fewer than 4 bytes remaining, only those bytes are XORed.
Limitations
- Works only on POSIX-compatible systems (Linux, macOS)
- Assumes int is 4 bytes and little-endian architecture
- The file is modified in-place — no backups or safety checks