In this tutorial, you'll learn how to decrypt the contents of an encrypted text file using the C programming language. This is the natural companion to Assignment 11 (encrypt a text file). Because XOR is its own inverse, the decryption program is byte-for-byte identical to the encryption program — the same code that encrypted the file, run again with the same key, restores the plaintext. That symmetry is one of the most elegant properties of XOR-based stream ciphers, and it's why XOR appears at the heart of most real cryptographic algorithms.
📝 Problem Statement
Write a program in C to decrypt the contents of an encrypted text file.
⚙️ How the Program Works
The program is structurally the same as the encryption program from Assignment 11 — the only difference is the file you feed it. This is the whole point:
- Ask for the encrypted filename, the output filename, and the key.
- Open the encrypted file in binary read mode (
"rb"). - Open the output file in binary write mode (
"wb"). - Read the encrypted file one byte at a time with
fgetc(). - XOR each byte with the same key and write the result with
fputc(). The XOR operation undoes the encryption byte by byte. - Close both files when the end of the encrypted file is reached.
🔐 Why Decryption Is the Same as Encryption
XOR (exclusive-or) is a bitwise operation with a remarkable property: applying it twice with the same key returns the original value. For any two bytes p (plaintext) and k (key):
/* First application (encryption): */
c = p ^ k
/* Second application (decryption): */
p' = c ^ k
= (p ^ k) ^ k
= p ^ (k ^ k)
= p ^ 0
= p
Because k ^ k = 0 for every byte, the two XORs cancel out. That means the encryption function and the decryption function are literally the same code. If you wrote the encryption program from Assignment 11, you've already written the decryption program. This is not a shortcut — it's a fundamental property of the cipher.
Here's the byte arithmetic worked out for a few characters with key 'K' (0x4B):
| Plaintext | Plain (hex) | Key (hex) | Encrypted (hex) | Plaintext ^ Key |
|---|---|---|---|---|
| H | 0x48 | 0x4B | 0x03 | ✓ |
| e | 0x65 | 0x4B | 0x2E | ✓ |
| l | 0x6C | 0x4B | 0x27 | ✓ |
| o | 0x6F | 0x4B | 0x24 | ✓ |
Decrypting 0x03 with 0x4B: 0x03 ^ 0x4B = 0x48 — back to H. That's all there is to it.
💻 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 encrypted 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 encrypted file in binary read mode */
src = fopen(src_name, "rb");
if (src == NULL)
{
printf("Error: Could not open '%s'.\n", src_name);
return 1;
}
/* Open the output file 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 with the key, write one byte.
This is the exact same code as the encryption program. */
while ((ch = fgetc(src)) != EOF)
{
fputc(ch ^ key, dst);
bytes++;
}
fclose(src);
fclose(dst);
printf("%ld bytes decrypted from '%s' to '%s'.\n",
bytes, src_name, dst_name);
return 0;
}🖥️ Sample Output
Assume encrypted.bin was produced by Assignment 11 with key 'K'. It contains 13 bytes of binary data that correspond to the original plaintext "Hello, World!". Running the decryption program:
Enter the output filename: decrypted.txt
Enter the key (a single character): K
13 bytes decrypted from 'encrypted.bin' to 'decrypted.txt'.
The file decrypted.txt now contains the original message:
decrypted.txt:
Hello, World!
If you run the program with the wrong key, the output will be garbage — but the program won't report an error. That's a hallmark of XOR: it has no notion of "correct" or "incorrect" key; it just transforms whatever bytes you give it.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
fopen(src_name, "rb") |
Opens the encrypted file in binary read mode. The encrypted file contains arbitrary bytes that would be corrupted by text-mode translation. |
fopen(dst_name, "wb") |
Opens the output file in binary write mode. Even though the content is text, we don't know that until we've decrypted it — and the decrypted bytes may still include edge cases, so binary mode is the safe choice. |
scanf(" %c", &key) |
The leading space skips any whitespace left over from the previous scanf. Without it, the key would be the newline character (0x0A), not the character the user intended. |
while ((ch = fgetc(src)) != EOF) |
Reads one byte at a time. fgetc returns int so it can signal EOF distinctly from byte value 0xFF. |
fputc(ch ^ key, dst) |
This single line is the entire decryption. XORing the encrypted byte with the same key recovers the original plaintext byte. |
bytes++ |
Counts how many bytes were processed — useful for verification. |
fclose(src); fclose(dst); |
Flushes buffers and releases handles. Essential on binary files. |
🧠 Why the Same Code Works for Both
The confusion many beginners feel is: "If encryption and decryption are the same code, how does the program know which one to do?" The answer is that it doesn't need to. The program does one thing: XOR each byte with the key. Whether that results in a scrambled file or a restored file depends entirely on the input:
- If the input is plaintext, the output is ciphertext — the program is encrypting.
- If the input is ciphertext, the output is plaintext — the program is decrypting.
The operation is the same; only the "role" of the input changes. This is exactly why the two programs (11 and 13) look identical. In a production cryptosystem, you'd have separate encrypt() and decrypt() functions for clarity and to avoid confusion about key management, but under the hood they do the same XOR.
🐛 Common Pitfalls
- Using a different key: This is the most common mistake. The key must be identical to the one used during encryption, byte for byte. A single character difference produces garbage output.
- Using text mode for the encrypted file: On Windows, opening the encrypted file with
"r"instead of"rb"would translate0x0Abytes and truncate onCtrl+Z, corrupting the data. - Forgetting the leading space in
" %c": The newline character becomes the key. The decryption output then looks like garbage, but the program prints success. - Assuming a wrong key produces an error: XOR has no error-checking. A wrong key produces output that looks successful but is garbled — you need to inspect the output file.
- Decrypting into the same file: If you open the encrypted file for reading and writing, you'll overwrite the input before you've finished reading it. Always use a separate output file.
- Truncating the wrong file: Using
"w"on a filename that already exists destroys its content. Double-check the output filename before running.
💡 Tips & Best Practices
- Always use
"rb"/"wb"for anything involving encryption — the file may contain bytes that aren't valid text, even after decryption (e.g., if the key was wrong). - Print the byte count so you can compare against the encrypted file's size — a mismatch usually means a read/write error.
- If you want to make the program self-contained, add a "verify" step: after decryption, check that every byte is printable ASCII (or matches the expected file format). This catches wrong-key errors early.
- Keep the key out of source code and command history — read it from a file or prompt the user (as this program does).
- For real security, replace the XOR cipher with a proper crypto library (OpenSSL's AES-256-GCM is a standard choice).
- Compile with
gcc -Wall -Wextra -std=c11 -gto catch type warnings.
🔁 Combined Encrypt/Decrypt Program
Since the two operations are identical, the cleanest way to write them in a single program is to expose the operation via a command-line flag. Here's the pattern:
int main(int argc, char *argv[])
{
if (argc != 5)
{
printf("Usage: %s enc|dec in out key\n", argv[0]);
return 1;
}
const char *mode = argv[1];
if (strcmp(mode, "enc") != 0 && strcmp(mode, "dec") != 0)
{
printf("Error: mode must be 'enc' or 'dec'\n");
return 1;
}
int key = (unsigned char)argv[4][0];
/* ... open argv[2] for reading, argv[3] for writing,
loop and XOR each byte with key — same code for both modes ... */
}
The mode parameter is purely informative — the program does exactly the same thing either way. A message at the end can print "encrypted" or "decrypted" depending on mode, but the byte-level operation is unchanged.