summaryrefslogtreecommitdiffstats
path: root/Weekly Challenges/Week 3/Basic Encryption Fixed.py
blob: 97972416974d7f3aec905b55989e08c8ec953297 (plain)
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
# 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
print(chr(65535))
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

# 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)%65535)
        print((file_character_code + key_character_code),(file_character_code + key_character_code)%65535)
    else:
        encrypted_message += chr((file_character_code - key_character_code)%65535)
        print((file_character_code - key_character_code),(file_character_code - key_character_code)%65535)

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.")