C Program For Encryption And Decryption
Data security is paramount in our digital world, from personal messages to sensitive corporate information. Understanding the fundamentals of how data can be protected is crucial for anyone working with information. In this article, you will learn how to implement basic encryption and decryption techniques using the C programming language.
Problem Statement
In an era where data breaches are common, ensuring the confidentiality and integrity of information is a critical challenge. Whether transmitting data over a network or storing it on a device, there's a constant need to protect it from unauthorized access. This requires methods to transform readable data (plaintext) into an unreadable format (ciphertext) and vice-versa, which is where encryption and decryption come into play.
Example
Consider encrypting the word "HELLO" with a simple shift cipher (like a Caesar cipher with a shift of 3).
Input: HELLO
Key: 3
Output: KHOOR (H+3=K, E+3=H, L+3=O, L+3=O, O+3=R)
Background & Knowledge Prerequisites
To effectively follow this article, readers should have a basic understanding of:
- C Programming Fundamentals: Variables, data types (especially
char), loops (for,while), conditional statements (if-else), functions, and basic input/output operations (printf,scanf,fgets). - Character Encoding: How characters are represented numerically (e.g., ASCII values). This is fundamental for character manipulation.
- Modulo Operator (%): Used to wrap around alphabets or other numeric ranges.
Use Cases or Case Studies
Basic encryption and decryption techniques, even simple ones, find application in various scenarios:
- Securing Basic Text Messages: Implementing a simple chat application where messages are lightly obfuscated before sending.
- Password Hashing (Simplified): While not truly secure for production, basic ciphers can illustrate the concept of transforming passwords before storage (though real systems use cryptographic hashes).
- Obfuscating Configuration Files: Protecting sensitive settings in a software application from casual inspection.
- Educational Purposes: Demonstrating core cryptographic principles in computer science courses.
- Simple File Protection: Applying a basic cipher to small text files to prevent direct reading by unauthorized users.
Solution Approaches
We will explore two fundamental, easy-to-understand encryption and decryption methods in C: the Caesar Cipher and the XOR Cipher.
Approach 1: Caesar Cipher (Substitution Cipher)
Summary: This method shifts each letter in the plaintext by a fixed number of positions down or up the alphabet. It's one of the simplest and oldest forms of encryption.
// Caesar Cipher Encryption and Decryption
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For isalpha, isupper, islower
// Function to encrypt a message using Caesar Cipher
void encryptCaesar(char text[], int key) {
int i;
for (i = 0; text[i] != '\\0'; ++i) {
char ch = text[i];
// Encrypt uppercase letters
if (isupper(ch)) {
ch = (char)(((ch - 'A' + key) % 26) + 'A');
}
// Encrypt lowercase letters
else if (islower(ch)) {
ch = (char)(((ch - 'a' + key) % 26) + 'a');
}
// Non-alphabetic characters remain unchanged
text[i] = ch;
}
}
// Function to decrypt a message using Caesar Cipher
void decryptCaesar(char text[], int key) {
int i;
for (i = 0; text[i] != '\\0'; ++i) {
char ch = text[i];
// Decrypt uppercase letters
if (isupper(ch)) {
ch = (char)(((ch - 'A' - key + 26) % 26) + 'A'); // Add 26 to handle negative results of (ch - 'A' - key)
}
// Decrypt lowercase letters
else if (islower(ch)) {
ch = (char)(((ch - 'a' - key + 26) % 26) + 'a'); // Add 26 for similar reasons
}
text[i] = ch;
}
}
int main() {
// Step 1: Declare variables for message and key
char message[100];
int key;
printf("Enter a message to encrypt: ");
fgets(message, sizeof(message), stdin);
message[strcspn(message, "\\n")] = 0; // Remove trailing newline
printf("Enter key (an integer): ");
scanf("%d", &key);
key = key % 26; // Ensure key is within 0-25 range for alphabet wrap-around
// Step 2: Encrypt the message
char encryptedMessage[100];
strcpy(encryptedMessage, message); // Copy original message to encrypt
encryptCaesar(encryptedMessage, key);
printf("Encrypted message: %s\\n", encryptedMessage);
// Step 3: Decrypt the message
char decryptedMessage[100];
strcpy(decryptedMessage, encryptedMessage); // Copy encrypted message to decrypt
decryptCaesar(decryptedMessage, key);
printf("Decrypted message: %s\\n", decryptedMessage);
return 0;
}
Sample Output:
Enter a message to encrypt: HELLO World
Enter key (an integer): 3
Encrypted message: KHOOR Zruog
Decrypted message: HELLO World
Stepwise Explanation:
encryptCaesar(char text[], int key)Function:
- Iterates through each character of the input
text. - Checks if the character is an uppercase or lowercase letter using
isupper()andislower()from. - For uppercase, it shifts the character's ASCII value by
keypositions, wraps around using the modulo26(for 26 letters in the alphabet), and converts it back to an uppercase letter.(ch - 'A')converts 'A' to 0, 'B' to 1, etc., allowing for modulo arithmetic. - Similar logic applies to lowercase letters, using
'a'as the base. - Non-alphabetic characters are left unchanged.
decryptCaesar(char text[], int key)Function:
- Follows a similar iterative structure.
- For decryption, the
keyis subtracted. To handle potential negative results (e.g., if'A' - keygoes below 'A'),+ 26is added before the modulo operation, ensuring the result is always positive before adding back the base character ('A'or'a').
main()Function:
- Prompts the user for a message and an integer key.
- Copies the original message to
encryptedMessageand callsencryptCaesar. - Copies the encrypted message to
decryptedMessageand callsdecryptCaesar. - Prints both the encrypted and decrypted results. The key is modulated by 26 (
key = key % 26;) to ensure it stays within a valid range for alphabet shifts.
Approach 2: XOR Cipher
Summary: The XOR (exclusive OR) cipher is a simple symmetric encryption algorithm where plaintext is combined with a key using the XOR bitwise operation. A key property of XOR is that applying it twice with the same key restores the original value ( A ^ B ^ B = A ).
// XOR Cipher Encryption and Decryption
#include <stdio.h>
#include <string.h>
// Function to encrypt/decrypt a message using XOR cipher
void xorCipher(char text[], char key_char) {
int i;
for (i = 0; text[i] != '\\0'; ++i) {
text[i] = text[i] ^ key_char; // XOR each character with the key
}
}
int main() {
// Step 1: Declare variables for message and key
char message[100];
char key_char; // Single character key for simplicity
printf("Enter a message to encrypt: ");
fgets(message, sizeof(message), stdin);
message[strcspn(message, "\\n")] = 0; // Remove trailing newline
printf("Enter a single character key: ");
scanf(" %c", &key_char); // Note the space before %c to consume newline
// Step 2: Encrypt the message
char encryptedMessage[100];
strcpy(encryptedMessage, message); // Copy original message
xorCipher(encryptedMessage, key_char);
printf("Encrypted message: %s\\n", encryptedMessage);
// Step 3: Decrypt the message (XOR is symmetric, same function)
char decryptedMessage[100];
strcpy(decryptedMessage, encryptedMessage); // Copy encrypted message
xorCipher(decryptedMessage, key_char); // Apply XOR again
printf("Decrypted message: %s\\n", decryptedMessage);
return 0;
}
Sample Output:
Enter a message to encrypt: Secret Message!
Enter a single character key: X
Encrypted message: #&%'$T
#
Decrypted message: Secret Message!
*(Note: The encrypted output for XOR often contains non-printable characters, which might display strangely in a console, but the decryption restores the original.)*
Stepwise Explanation:
xorCipher(char text[], char key_char)Function:
- Takes the
textand akey_charas input. - Iterates through each character in the
text. - Applies the bitwise XOR (
^) operator between the current character and thekey_char. The result is stored back intotext[i]. - This single function performs both encryption and decryption due to the symmetric property of XOR.
main()Function:
- Prompts the user for a message and a single character key. The
scanf(" %c", &key_char);includes a space before%cto consume any leftover newline character from the previousfgets, preventing it from being read as the key. - Copies the original message, then calls
xorCipherto encrypt it. - Copies the encrypted message, then calls
xorCipheragain (with the *same* key) to decrypt it. - Prints both the encrypted and decrypted results.
Conclusion
Implementing basic encryption and decryption techniques in C, such as the Caesar cipher and the XOR cipher, provides a fundamental understanding of how data can be transformed for security purposes. While these methods are too simple for robust real-world security, they are excellent starting points for grasping the core concepts of cryptography. They highlight character manipulation, bitwise operations, and the importance of a key in securely transforming information.
Summary
- Encryption and decryption protect data confidentiality by transforming plaintext into ciphertext and vice-versa.
- The Caesar cipher is a substitution cipher that shifts letters by a fixed key.
- XOR cipher uses the bitwise XOR operation between plaintext characters and a key, offering symmetric encryption/decryption.
- Basic understanding of C programming, character encoding, and the modulo operator are essential prerequisites.
- These methods, though simple, demonstrate core cryptographic principles and are useful for educational purposes and light data obfuscation.