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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
# Problems I can think of...
# 1. We currently are not wrapping around character; i.e. if the original message/character plus the
# key character is greater than 65535 we will crash. Thankfully it will just crash and the
# original message will not be overridden.
# 2. If the user enters the wrong key to decrypt, they then have to re-encrypt it with that wrong
# key and then decrypt it back. Solution: hash and salt the key, and then compare it with that
# hash/salt before using it
import os
import hashlib
MIN_CHARACTER = 0x0
MAX_CHARACTER = 0x110000
def hash_key(key):
return hashlib.sha256(key.encode("ascii")).hexdigest()
print("Select one of the following options:\n1. Encrypt a file\n2. Decrypt a file")
is_encrypting = None
while is_encrypting is None:
selection = input("Enter the selection number: ")
if selection == "1":
is_encrypting = True
elif selection == "2":
is_encrypting = False
else:
print("Invalid selection! Please try again.")
file_name = input("Enter the file name: ")
key = input("Enter the key: ")
file_contents = None
if os.path.exists(file_name + ".key"):
if is_encrypting:
print("File was already encrypted")
quit()
else:
with open(file_name + ".key", "r", encoding = "utf-8") as f:
if hash_key(key) != f.read():
print("Wrong key")
quit()
os.remove(file_name + ".key")
else:
if is_encrypting:
with open(file_name + ".key", "w", encoding = "utf-8") as f:
f.write(hash_key(key))
else:
print("File is not encrypted")
quit()
# Reading in the file contents
with open(file_name, "r", encoding="utf-8") as f:
file_contents = f.read()
# Encryption of the file contents
encrypted_message = ""
# chr() num to letter
# ord() letter to num
for i in range(len(file_contents)):
file_character_code = ord(file_contents[i])
key_character_code = ord(key[i%len(key)])
if is_encrypting:
encrypted_message += chr((file_character_code + key_character_code) % MAX_CHARACTER)
else:
encrypted_message += chr((file_character_code - key_character_code) % MAX_CHARACTER)
with open(file_name, "w", encoding="utf-8") as f:
f.write(encrypted_message)
if is_encrypting:
print(f"The file, {file_name}, is now encrypted.")
else:
print(f"The file, {file_name}, is now decrypted.")
|