I’m stuck with a decryption problem I’m having. I have a really basic cipher that is only the alphabet and is offset by 1 letter, like this:
A B
B C
C D
D E
to z to A
the right column is the letters I’m given, and I need to turn them to the letters on the left.
I’m reading this from a file, and saving each column into a list like this
#!/usr/bin/python
key = "key.txt"
encrypted = "encrypted.txt"
decrypted = "decrypted.txt"
encryptedList = []
decryptedList = []
with open(key, "r") as file:
for line in file:
currentLine = line.split()
currentDecrypted = currentLine[0]
currentEncrypted = currentLine[1]
decryptedList.append(currentEncrypted)
encryptedList.append(currentDecrypted)
file.close()
counter = 0
with open(encrypted, "r") as file:
for line in file:
currentLine = line
for letter in currentLine:
currentLetter = letter
for item in encryptedList:
if(item == currentLetter):
####here's where the problem starts####
####I've tried just printing counter, and I get mostly go
printencryptedList[counter-1]
counter = 0
break
counter += 1
what I’m trying to decrypt is a text file that looks like this
FMMP
NZ OBNF JT KSMBB
KPIO TVDLT BQQ
GWWWWWWBMT PG DJJJJJH
I get the correct count numbers for FMMP, (5, 12, 12, 15) with counter -1, but then i get 39, 25,40 and so on. Any help would be greatly appreciated, and let me know if you need more info.
I also welcome ideas on better/easier ways to do this, but I would also like a solution similar to this, so I can figure out what’s going on here. Thanks
Alright, thanks for all the answers and info. I’m posting what I finally did and it works. I’m sure it’s not as pythonic as it should be, but I implemented a few things that people mentioned. Thanks for the info.
import string
key = "key.txt"
encrypted = ""encrypted.txt"
decrypted = "decrypted.txt
encryptedString = ""
decryptedString = ""
keyDict = {}
with open(key, "r") as file:
for line in file:
currentLine = line.split()
currentDecrypted = currentLine[0]
currentEncrypted = currentLine[1]
keyDict[currentDecrypted] = currentEncrypted
with open(encrypted, "r") as file:
for line in file:
currentLine = line
for letter in currentLine:
currentLetter = letter
encryptedString += letter
for key in keyDict:
if(keyDict[key] == letter):
decryptedString += key
break
elif(letter == " "):
decryptedString += " "
break
elif(letter == "\n"):
decryptedString += "\n"
break
with open(decrypted, "a") as file:
file.write(decryptedString)
You definitely should use dictionaries. Together with Pythons
map(), your task is really simple:I won’t post the result of the decryption here as I don’t have a “Parental Advisory”-sticker atm. 😉 Just try it!
Of course there are helper functions in the
string-module, but OP wants to learn python, not implement a “bullet-proof” cryptographic system.