i was going through one of the python recipes in active state and found the following code. I've come up with the following 4 questions. Will be very grateful for any guidance and explanations.
Q::Im unable to exactly figure out as to why is a "key-random seed" taken from the user at the first place in line "k=long(sys.argv[2])" ? especially since, this value 'k' doesnt seemed to be used in the later part of the code ?
Secondly, in the part of the code for encryption and decryption, what is the exact implication of the statement "bytearray[i]-random.randint(0,255)%256" ? does this mean that the unicode values of each character is shifted or displaced during encryption and re-shifted back to its original value when decrypted ?
Thirdly, does the "bytearray= map(ord, f1.read())" compute the unicode point values of every character in the file ?
Lastly, Since random numbers are used in the encryption and decryption, what factor guarantees that the decryption of the encrypted file will be accurate ? has the seed value "k" got anything to do with this ?
Below is the code that i'm studying.
Will greatly appreciate your guidance,Thanks in advance
# encdec.py
import sys
import random
if len(sys.argv) != 5:
print "Usage: encdec.py e/d longintkey [path]filename1 [path]filename2"
sys.exit()
k = long(sys.argv[2]) # key
random.seed(k)
f1 = open( sys.argv[3], "rb")
bytearr = map (ord, f1.read () )
f2 = open( sys.argv[4], "wb" )
if sys.argv[1] == "e": # encryption
for i in range(len(bytearr)):
byt = (bytearr[i] + random.randint(0, 255)) % 256
f2.write(chr(byt))
if sys.argv[1] == "d": # decryption
for i in range(len(bytearr)):
byt = ((bytearr[i] - random.randint(0, 255)) + 256 ) % 256
f2.write(chr(byt))
f1.close()
f2.close()