Decrypt an Encrypted Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Decrypt the Contents of an Encrypted Text File

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.

C program to decrypt the contents of an encrypted text file using the symmetric XOR cipher with fgetc and fputc, with step-by-step explanation.

📝 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:

  1. Ask for the encrypted filename, the output filename, and the key.
  2. Open the encrypted file in binary read mode ("rb").
  3. Open the output file in binary write mode ("wb").
  4. Read the encrypted file one byte at a time with fgetc().
  5. XOR each byte with the same key and write the result with fputc(). The XOR operation undoes the encryption byte by byte.
  6. 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.

⚠️ Important: A single-byte XOR cipher is not secure. Its output is trivially breakable by frequency analysis. This exercise teaches the shape of a stream cipher — the same read-XOR-write pattern that underlies AES-CTR, ChaCha20, and every practical stream cipher — but real security requires a proper library like OpenSSL.

💻 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:

Console: Enter the encrypted filename: encrypted.bin
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:

Contents of 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 translate 0x0A bytes and truncate on Ctrl+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 -g to 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.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 11. Encrypt the Contents of a Text File
  • 15. Copy the Contents of One Text File into Another
  • 8. Read Binary Data from a Binary File and Display It
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 12. Sort the Lines of a Text File in Alphabetical Order   ||   Next Problem: -->> 14. Append Text to an Existing Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.