-
Notifications
You must be signed in to change notification settings - Fork 3
/
fileencrypt.py
45 lines (37 loc) · 1.19 KB
/
fileencrypt.py
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
34
35
36
37
38
39
40
41
42
43
44
45
from simplecrypt import encrypt, decrypt
from os.path import exists
from os import unlink
PASSWORD = "secret"
FILENAME = "encrypted.txt"
def main():
# read or create the file
if exists(FILENAME):
print("reading...")
data = read_encrypted(PASSWORD, FILENAME)
print("read %s from %s" % (data, FILENAME))
n_bottles = int(data.split(" ")[0]) - 1
else:
n_bottles = 10
# write the file
if n_bottles > 0:
data = "%d green bottles" % n_bottles
print("writing...")
write_encrypted(PASSWORD, FILENAME, data)
print("wrote %s to %s" % (data, FILENAME))
else:
unlink(FILENAME)
print("deleted %s" % FILENAME)
def read_encrypted(password, filename, string=True):
with open(filename, 'rb') as input_file:
ciphertext = input_file.read()
plaintext = decrypt(password, ciphertext)
if string:
return plaintext.decode('utf8')
else:
return plaintext
def write_encrypted(password, filename, plaintext):
with open(filename, 'wb') as output:
ciphertext = encrypt(password, plaintext)
output.write(ciphertext)
if __name__ == '__main__':
main()