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.

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

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

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 7**–**8:**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

TRENDING TOPICS