Blog | G5 Cyber Security

XOR Cipher: Encrypt & Decrypt Messages

TL;DR

This guide shows you how to encrypt and decrypt messages using a simple XOR cipher in Python. It works by combining your message with a secret key, making it unreadable without the key.

What is an XOR Cipher?

XOR (exclusive OR) is a bitwise operation. When applied to text, it changes each character based on a key. The same key can be used for both encryption and decryption. It’s basic but demonstrates core cryptography principles.

Step 1: Understanding the Concept

The XOR cipher works like this:

To decrypt, you XOR the encrypted message with the *same* key again.

Step 2: Python Code for Encryption

def encrypt(message, key):
    key_length = len(key)
    encrypted_message = ''
    for i in range(len(message)):
        char_code = ord(message[i])  # Get ASCII value of the message character
        key_char_code = ord(key[i % key_length]) #Get ASCII value of the key character, repeating if needed
        encrypted_char_code = char_code ^ key_char_code # XOR operation
        encrypted_message += chr(encrypted_char_code)  # Convert back to a character
    return encrypted_message

This function takes your message and key as input. It loops through each character of the message, encrypts it using the corresponding character from the key (repeating the key if it’s shorter than the message), and builds up the encrypted message.

Step 3: Python Code for Decryption

def decrypt(encrypted_message, key):
    key_length = len(key)
    decrypted_message = ''
    for i in range(len(encrypted_message)):
        char_code = ord(encrypted_message[i]) # Get ASCII value of the encrypted character
        key_char_code = ord(key[i % key_length]) #Get ASCII value of the key character, repeating if needed
        decrypted_char_code = char_code ^ key_char_code # XOR operation
        decrypted_message += chr(decrypted_char_code)  # Convert back to a character
    return decrypted_message

The decryption function is almost identical to the encryption function. It takes the encrypted message and the *same* key as input, performs the XOR operation again, and recovers the original message.

Step 4: Example Usage

message = "This is a secret message."
key = "mysecretkey"

encrypted_message = encrypt(message, key)
print("Encrypted:", encrypted_message)

decrypted_message = decrypt(encrypted_message, key)
print("Decrypted:", decrypted_message)

This example shows how to use the functions. You’ll see that the decrypted message matches the original.

Step 5: Important Considerations

Exit mobile version