-1

Sort of stumped here, can't find out how to undo the process done in the selection for "E" in "D". option D is supposed to decrypt while option E encrypts. Option E works as intended, but I can't figure out how I would undo it.

Selection = input('Are you decrypting or encrypting a file? Type E for encrypt, or D for decrypt\n')
if Selection == "E":
    f = open('HolocronMessage.txt','r')
    JediMessage = readLinesFromFile()
    #print(JediMessage) -- LOL DEBUG
    JediEncrypted = ""
    for i in JediMessage:
            JediEncrypted += chr(ord(i) - 3)
            JediMessage = ''.join(format(ord(i), '08b') for i in JediEncrypted)
            with open('HolocronMessage.txt', 'w') as f:
                f.write(JediMessage)

    print(JediMessage)
elif Selection == "D":
    f = open('HolocronMessage.txt','r')
    JediMessage = readLinesFromFile()
    JediDecrypted = ""
    for i in JediMessage:
            JediDecrypted += chr(ord(i) + 3)
            JediMessage = ''.join(format(ord(i), '08b') for i in JediDecrypted)
            with open('HolocronMessage.txt', 'w') as f:
                f.write(JediMessage)
else:
    print("Invalid selection. Please return a valid seleciton.")

I am trying to make a decryption function starting at line 24 where the text file that was written is undone and the original message is returned.

I assume it has to do with changing line 30 with its inverse? JediMessage = ''.join(format(ord(i), '08b')

Cloud
  • 1
  • 1

1 Answers1

0

I don't want to post an answer, but I guess this is too long for a comment.

First, what is readLinesFromFile's definition? You called it without argument, are you sure it is working as intended?

Second, why do you convert codepoint to a character and concatenate to a string then iterate through the characters of the string and operate on codepoints? Why not stick with codepoints? And don't use format codepoints into 8bit binary strings, Unicode characters with codepoints greater than 255 will break your encoding.

Finally, you are doing decryption wrong, to decrypt, just do the reverse operation of each operation applied during encryption in reverse order.

Example code:

def encrypt(s):
    return ''.join(f'{i-3:08b}' for i in s.encode('utf8'))

def decrypt(s):
    return bytearray([int(s[i:i+8], 2) + 3 for i in range(0, len(s), 8)]).decode('utf8')

Example:

In [18]: def encrypt(s):
    ...:     return ''.join(f'{i-3:08b}' for i in s.encode('utf8'))
    ...:
    ...: def decrypt(s):
    ...:     return bytearray([int(s[i:i+8], 2) + 3 for i in range(0, len(s), 8)]).decode('utf8')

In [19]: encrypt('Ξένη Γήινος')
Out[19]: '110010111001101111001011101010101100101110111010110010111011010000011101110010111001000011001011101010111100101110110110110010111011101011001011101111001100110001111111'

In [20]: decrypt(_)
Out[20]: 'Ξένη Γήινος'

In [21]:
Ξένη Γήινος
  • 2,181
  • 1
  • 9
  • 35