Lab 14a - XOR Encryption in Python
Lab 14a - XOR Encryption in Python
)
What You Need
A Kali Linux machine, real or virtual. You could also use OS X, or Windows with Python installed.
Purpose
Encrypt and decrypt files using XOR in Python.
Understanding XOR
Exclusive OR (XOR) is a fundamental mathematical operation used in many encryption algorithms.
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
For our purposes, we'll use the Python ^ operator, which acts on a whole byte at a time.
A is 01000001
B is 01000010
C is 01000011
...
A whole table of ASCII values is here:
http://www.asciitable.com/
Consider A^B:
A is 01000001
B is 01000010
A^B= 00000011
That is character 3, an unprintable end-of-text mark.
A is 01000001
s is 01110011
A^B= 00110010
The result is the hexadecimal value 0x32, or the numeral 2.
XOR in Python
In Kali Linux, in a Terminal window, execute this command:
nano xor1
#!/usr/bin/python
import sys
if len(sys.argv) != 4:
print "Usage: ./xor1 infile outfile k"
print "k is a one-character XOR key"
print "For hexadecimal keys, use $'\\x01'"
exit()
f = open(str(sys.argv[1]), "rb")
g = open(str(sys.argv[2]), "a")
k = ord(sys.argv[3])
try:
byte = f.read(1)
while byte != "":
xbyte = ord(byte) ^ k
g.write(chr(xbyte))
byte = f.read(1)
finally:
f.close()
g.close()
Save the file with Ctrl+X, Y, Enter. Next, we need to make the file executable.
./xor1
You see the help message, explaining how to use the program, as shown below.
To create a file named plain1 with the letter A in it, execute these commands :
cat plain1
The "echo -n" command created a file named plain1 which contains a single letter A, without a carriage return at the end of the
file.
The "cat plain1" command printed out the file, which appeared as a single A at the start of the next line, as shown below:
cat cipher1
nano plain2
In nano, enter the code shown below, replacing "YOUR NAME" with your own name:
cat cipher2
cat plain2r