Hossam Hamdy

Posted on

# XOR Encryption in Python3

Hi Folks, In my article I will explain to you how to encrypt texts with XOR encryption using python 3.

first we have to import those modules

# 1- importing area

In the previous section we import the string module to be able to use all upper and lower case letters, numbers and signs to generate the encryption/decryption key.

We also import the random module to generate a random string of those letters, numbers and symbols so that we can create a random decryption key every time.

# 2- Generate Random Key Function.

In the previous section, we created a function that:
– Receive parameter named size which is considered the length of the encryption key to be generated.
– Then it generate the key from a set of letters, numbers and signs that we typed in the previous code
– Returns the generated key.

[ The length of the key is very important, for example if you want to encrypt a text consisting of 100 characters and the length of the key consists of 50 characters, then only 50 characters of the text will be encrypted ]

# 3- XOR Encryption Function.

Now the most important part of the article is the encryption and decryption function.
here the enc_XOR function receive 2 parameters: Text, Key.

Bitwise operators works on bits and performs bit-by-bit operation. For each character in text and another one of the key It will be processed through the XOR (^) Bitwise Operator and you can read more about the XOR Bitwise Operator in python @ Python Bitwise Operators

We will talk about XOR operator example:
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0

[1] An example about encryption:
a(Text) = 0011 1100
b(Key) = 0000 1101
a^b(Encrypted Text) = 0011 0001

[2] An example about decryption:
c(Encrypted Text) = 0011 0001
b(Key) = 0000 1101
c^b = 0011 1100 = a(Clear Text)

So if we pass a clear text with a key it will be encrypted & If we pass the encrypted text with the same key it will be decrypted.

# 4- Output Area.

Actually, In this section we are only print the outputs 😂
But notice something that we pass the encrypted text(encrypted_text) and key in the encryption function to reverse its effect.

# [+] The End.

I hope you understood the article well and achieved the benefit you hoped for.
You will find the script on my GitHub Account @nullx33f

Thanks for reading. 💙

.

great article.