XOR Encryption of plaintext with a key in Python

A simple yet effective encryption method, XOR, uses bit-level operations based on the printed letter's ASCII values. The XOR encryption technique uses a special key to create the encrypted text, which is then XOR-ed with the plaintext. After determining the plaintext and key lengths, the plaintext is divided into segments that are the same length as the key. The results of the XOR operation between each segment and the key are then saved in an array. After all operations are finished, the array holds the final encrypted text.

Although XOR encryption is straightforward and helpful in explaining the fundamentals of encryption, there are more secure methods for protecting sensitive data.

Code example

Let's see an example of performing XOR encryption on a plaintext.

# Function to perform XOR encryption
def xor_encryption(text, key):
# Initialize an empty string for encrypted text
encrypted_text = ""
# Iterate over each character in the text
for i in range(len(text)):
encrypted_text += chr(ord(text[i]) ^ ord(key[i % len(key)]))
# Return the encrypted text
return encrypted_text
# The plaintext that we want to encrypt
plain_text = "Educative Accelerates Developer Productivity"
# The secret key used for encryption
key = "Edu_key"
# Encrypt the plain_text using the key
encrypted_text = xor_encryption(plain_text, key)
# Print the encrypted text
print(f'Encrypted Text: {encrypted_text}')

Explanation

Let’s see the above code in detail.

  • Line 2: We define a function named xor_encryption which takes two arguments: text and key.

  • Line 4: We declared an empty string encrypted_text which will hold the final encrypted result.

  • Lines 78: The loop iterates over the text, XORs each character with the corresponding character in the key, and appends the result to encrypted_text.

  • Line 19: The xor_encryption function is called with plain_text and key.

Copyright ©2024 Educative, Inc. All rights reserved