-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathmodify.py
23 lines (19 loc) · 909 Bytes
/
modify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def modify_file_inplace(filename, crypto, blocksize=16):
'''
Open `filename` and encrypt/decrypt according to `crypto`
:filename: a filename (preferably absolute path)
:crypto: a stream cipher function that takes in a plaintext,
and returns a ciphertext of identical length
:blocksize: length of blocks to read and write.
:return: None
'''
with open(filename, 'r+b') as f:
plaintext = f.read(blocksize)
while plaintext:
ciphertext = crypto(plaintext)
if len(plaintext) != len(ciphertext):
raise ValueError('''Ciphertext({})is not of the same length of the Plaintext({}).
Not a stream cipher.'''.format(len(ciphertext), len(plaintext)))
f.seek(-len(plaintext), 1) # return to same point before the read
f.write(ciphertext)
plaintext = f.read(blocksize)