File encryption/decryption using stream cipher. It can encrypt/decrypt any type of file.
Python, 33 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
# encdec.py # File encryption/decryption using stream cipher # FB - 201003066 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) # key random.seed(k) f1 = open( sys.argv, "rb") bytearr = map (ord, f1.read () ) f2 = open( sys.argv, "wb" ) if sys.argv == "e": # encryption for i in range(len(bytearr)): byt = (bytearr[i] + random.randint(0, 255)) % 256 f2.write(chr(byt)) if sys.argv == "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()
Tags: encryption, files, math
Here is an even shorter version:
One time pads must be generated via a real random process, not a pseudorandom number generator. The way you use the PRNG here would be classified as a stream cipher, not a one time pad. However, the PRNG used by Python has linearities that can be used to determine the state of the generator. It is clearly documented as not being suitable for cryptographic use. This approach is vulnerable to many attacks and should not be considered at all secure.
All true. What I really meant was the way, how enc/dec of each byte is done, is like one-time pad. True implementation of one-time would require asking user a random string/file that is the same size as the file to enc/dec, which is quite impractical. Of course I would not want anyone to use this code for serious encryption needs also. Thanks.
Actually I think the encryption strength can easily be increased (exponentially!) by encrypting the same file multiple times using a different key everytime. (For decryption, the keys must be applied in reverse order of course.) (Also it surely would be better to use a new random number generator algorithm that is specifically designed for cryptography.)
I found that your code must be changed a little in Python 3.1.2, just so: