XOR “Encryption” in C: An Old Trick and an Inside Joke
This example began as an inside joke with my boss: if we were going to add encryption, why not use one of the oldest tricks still rattling around the toolbox? XOR is a useful way to learn how bytes and reversible transformations work, but a fixed repeating key does not provide meaningful security.
The XOR Transformation
#include <stdio.h>
#include <string.h>
#define KEY 0xAA // Simple XOR key
// Function to encrypt and decrypt data using XOR
void xor_encrypt_decrypt(char *data, size_t len, char key) {
for (size_t i = 0; i < len; i++) {
data[i] ^= key;
}
}
int main() {
char message[] = "Hello, World!";
size_t len = strlen(message);
printf("Original message: %s\n", message);
// Encrypt the message
xor_encrypt_decrypt(message, len, KEY);
printf("Encrypted message: %s\n", message);
// Decrypt the message
xor_encrypt_decrypt(message, len, KEY);
printf("Decrypted message: %s\n", message);
return 0;
}
Let's break down the code:
#include <stdio.h>: Includes the standard input/output library.#include <string.h>: Includes the string handling library.#define KEY 0xAA: Defines the XOR key for encryption and decryption.void xor_encrypt_decrypt(char *data, size_t len, char key): Function to encrypt and decrypt data using XOR.int main(): The main function where the program execution begins.char message[] = "Hello, World!";: Declares a message to be encrypted and decrypted.size_t len = strlen(message);: Calculates the length of the message.printf("Original message: %s\n", message);: Prints the original message.xor_encrypt_decrypt(message, len, KEY);: Encrypts the message using the XOR key.printf("Encrypted message: %s\n", message);: Prints the encrypted message.xor_encrypt_decrypt(message, len, KEY);: Decrypts the message using the XOR key.printf("Decrypted message: %s\n", message);: Prints the decrypted message.return 0;: Exits the program.
Compiling and Running the Code
To compile and run the provided C source code for the ARM64 architecture, follow these steps:
# Compile the code
gcc -o xor_encryption xor_encryption.c
# Run the code
./xor_encryption
This compiles the XOR example and displays the original, transformed, and restored messages. The same operation reverses itself because A XOR K XOR K equals A.
Where Real Encryption Begins
Modern applications need authenticated encryption: confidentiality plus a reliable way to detect modification. They also need unique nonces and keys generated from a cryptographically secure source. The next article, Authenticated Encryption with libsodium in C, replaces the joke key with a modern, misuse-resistant library interface.
dispelled