I have the following python code:
file = open("encryption.txt","r")
str1 = file.read()
file.close
charList = []
for char in str1:
charList.append(char)
bits = []
ascList = []
for i in range(len(charList)):
ascList.append(ord(charList[i]))
ascList[i] = "{0:08b}".format(ascList[i])
currentAsc = ascList[i]
currentStr = str(currentAsc)
for x in range(len(currentStr)):
currentChar = currentStr[x]
bits.append(int(currentChar))
keyChar = input("enter the character that should act as the key: ")
keyAsc = "{0:08b}".format(ord(keyChar))
keyStr = str(keyAsc)
keyBits = []
for x in range(len(keyStr)):
keyBits.append(int(keyStr[x]))
key = []
while len(key) != len(bits):
for i in range(len(keyBits)):
key.append(keyBits[i])
resultBits = []
for i in range(len(bits)):
if key[i] != bits[i]:
resultBits.append("1")
else:
resultBits.append("0")
resultSplitInt = []
resultInt = ''.join(resultBits)
for i in range(0,len(resultInt), 8):
resultSplitInt.append(resultInt[i:i+8])
resultSplit = []
for i in range(len(resultSplitInt)):
resultSplit.append(chr(int(resultSplitInt[i],2)))
result = ''.join(resultSplit)
file = open("encryption.txt","w")
print(str1)
print("--------------------")
print(result)
file.write(result)
print("done")
file.close()
running the program once should change the contents of "encryption.txt" based on the key, and running the program again should return the contents to their original form.
however, when I actually run the code, some letters are swapped out.
for example: if the contents are "hello world" and I use the key "a" after running the code twice I am left with "hekko workd"
why does this happen, and how can I fix it?
p.s. I am aware that this is neither a secure encryption algorithm nor is my code very efficient. I am new to python and thought this would be a fun task to try. I got this far and can't find any reasons why it isn't working