In this tutorial, you'll learn how to encrypt the contents of a text file using the C programming language. The program reads the source file one byte at a time, applies a simple XOR cipher with a single-byte key, and writes the encrypted bytes to a new file. XOR encryption is the classic introduction to cryptography: it's easy to understand, easy to implement, and — most importantly — easy to decrypt. The same operation that encrypts the file will also decrypt it when you XOR with the same key.
📝 Problem Statement
Write a program in C to encrypt the contents of a text file.
⚙️ How the Program Works
The program follows a simple read-transform-write loop:
- Ask for the source filename, the output filename, and the key (a single character or integer).
- Open the source file in binary read mode (
"rb"). Binary mode is important — encrypted bytes may include values that text mode would translate or truncate. - Open the destination file in binary write mode (
"wb"). - Read the source one byte at a time with
fgetc(). - XOR each byte with the key and write the result with
fputc(). - Close both files when the end of the source is reached.
🔐 What Is XOR Encryption?
XOR (exclusive-or) is a bitwise operation with one extremely useful property: applying it twice with the same key undoes the first application. For any two bytes a and b:
/* XOR is its own inverse: */
(a ^ b) ^ b == a
That means the encryption function and the decryption function are the same code. If the plaintext is 'H' (0x48) and the key is 'K' (0x4B), the ciphertext is 0x03. XOR 0x03 with 0x4B again and you get 0x48 back. Here's the byte-level arithmetic for a few sample characters with key 'K':
| Character | ASCII (hex) | Key (hex) | Ciphertext (hex) | Encrypted char |
|---|---|---|---|---|
| H | 0x48 | 0x4B | 0x03 | (non-printable) |
| e | 0x65 | 0x4B | 0x2E | . |
| l | 0x6C | 0x4B | 0x27 | ' |
| o | 0x6F | 0x4B | 0x24 | $ |
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *src, *dst;
char src_name[100];
char dst_name[100];
int key;
int ch;
long bytes = 0;
printf("Enter the input filename: ");
scanf("%99s", src_name);
printf("Enter the output filename: ");
scanf("%99s", dst_name);
printf("Enter the key (a single character): ");
scanf(" %c", &key); /* leading space skips leftover newline */
/* Open source in binary read mode */
src = fopen(src_name, "rb");
if (src == NULL)
{
printf("Error: Could not open '%s'.\n", src_name);
return 1;
}
/* Open destination in binary write mode */
dst = fopen(dst_name, "wb");
if (dst == NULL)
{
printf("Error: Could not create '%s'.\n", dst_name);
fclose(src);
return 1;
}
/* Read one byte, XOR it, write one byte */
while ((ch = fgetc(src)) != EOF)
{
fputc(ch ^ key, dst);
bytes++;
}
fclose(src);
fclose(dst);
printf("%ld bytes encrypted from '%s' to '%s'.\n",
bytes, src_name, dst_name);
return 0;
}🖥️ Sample Output
Assume plain.txt contains a short message:
plain.txt:
Hello, World!
Running the program with key 'K':
Enter the output filename: encrypted.bin
Enter the key (a single character): K
13 bytes encrypted from 'plain.txt' to 'encrypted.bin'.
The file encrypted.bin now contains 13 bytes of binary data. Open it in a text editor and you'll see mostly unprintable characters — that's expected, because the ciphertext includes control bytes like 0x03 and 0x27. View it with xxd encrypted.bin | head to inspect the raw hex.
To decrypt, run the same program again with encrypted.bin as the input, a new output filename like decrypted.txt, and the same key 'K'. You'll get the original message back. This symmetric property is the point of Assignment 13.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
int key; |
The key is stored as int so the %c format specifier works, and so we can widen it later if needed. A single character is enough here. |
scanf(" %c", &key) |
The leading space in the format string skips any leftover whitespace — without it, the newline left over from the previous scanf would be read as the key. |
fopen(src_name, "rb") |
Binary read mode. On Windows, text mode would translate \r\n and might truncate data on Ctrl+Z. |
fopen(dst_name, "wb") |
Binary write mode. Creates the output file or truncates it if it already exists. |
while ((ch = fgetc(src)) != EOF) |
Reads one byte at a time. fgetc returns int so it can signal EOF distinctly from a valid byte 0xFF. |
fputc(ch ^ key, dst) |
XORs the byte with the key and writes the result. This single line is the entire cipher. |
bytes++ |
Counts how many bytes were processed — useful for verification and for debugging. |
fclose(src); fclose(dst); |
Flushes buffers and releases handles. Essential on binary files, where buffered writes may not have hit disk yet. |
📂 Why Binary Mode Is Essential
Encrypting a text file produces binary output — bytes that aren't valid printable characters. If you open the output with "w" (text mode) instead of "wb" (binary mode):
- On Windows, every
0x0Abyte would be automatically translated to0x0D 0x0A, silently corrupting the ciphertext. - Some library implementations may drop bytes that don't map to valid characters.
- When you later decrypt the file, the byte sequence no longer matches what you wrote, so the decryption output is garbled.
On Linux and macOS the difference is less visible, but using "rb"/"wb" is still the correct habit for any data that isn't guaranteed to be plain text.
🐛 Common Pitfalls
- Using text mode: The single most common bug. Always use
"rb"and"wb"when the output isn't guaranteed to be text. - Declaring
chaschar:fgetcreturnsint. If you declarechaschar, EOF (-1) may not be detected on systems wherecharis unsigned. - Encrypting the file in place: If you open the same file for both reading and writing, you'll corrupt the data. Always write to a different file, then swap if needed.
- Forgetting the leading space in
" %c": Without it, the newline left over from the previousscanfbecomes the key — resulting in encryption with key0x0Ainstead of the character you typed. - Using the wrong key for decryption: XOR is symmetric — decrypt with the same key. A different key produces garbage, not an error.
- Assuming the encrypted file is text: It isn't. Don't try to open it in a text editor or send it in a text email unless you encode it (e.g., base64).
🔑 Stronger Keys: Multi-Byte XOR
A single-byte key is trivially breakable by frequency analysis: the most common ciphertext byte almost certainly corresponds to the space character or 'e'. A slightly better version uses a multi-byte key repeated over the file:
const char *key = "SECRET";
size_t key_len = strlen(key);
size_t i = 0;
while ((ch = fgetc(src)) != EOF)
{
fputc(ch ^ key[i % key_len], dst);
i++;
}This still isn't secure against a determined attacker (the key can be recovered by factoring the ciphertext into a Vigenère-style analysis), but it raises the difficulty significantly and demonstrates the concept of key scheduling — a real cryptographic building block.
💡 Tips & Best Practices
- Use
"rb"/"wb"in all encryption programs, even if the input looks like text — encryption always produces binary output. - Check both
fopencalls forNULLand close the first file beforereturning on the second's failure. - Print the byte count so the user knows the operation actually processed something.
- Never encrypt the original file in place. Write to a new file, verify the output looks correct, then optionally
removethe plaintext. - For genuine protection, use OpenSSL's AES-256-GCM API — never roll your own crypto in production.
- Compile with
gcc -Wall -Wextra -std=c11 -gto catch type mismatches.