Reputation: 23
I am currently in the process of learning how to encrypt/decrypt using the Caesar Cipher Method in Python. I have worked through how to encrypt '14:00/the ships are in position' to receive '7,21,18,_6,21,22,3,6,_14,5,18,_22,1,_3,2,6,22,7,22,2,1' but am struggling with how to write the decryption code. Specifically, I am unsure how to use the if/else statement to properly reverse the original encryption and how to convert the numbers back into letters. Each letter will shift based on the hour(shift).
Decrypt code
import string
def decrypt(s):
s = "14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1"
shift = int(s[0:2])
time, plaintext = s.split("/")
print(shift)
print(time)
print(plaintext)
letters = string.ascii_lowercase
result = []
for char in plaintext:
print(char)
if char == '_':
result = result + ' '
else:
decode = (int(char) - shift) %26
result = result + str(decode) +','
print(result)
def main():
decode = decrypt("14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1")
main()
Upvotes: 0
Views: 383
Reputation: 15268
The main thing you need for your code are the ord
and chr
functions for generating characters, and to account for shifting by shift
being negative (you're on the right track with using modulus). Shortened version below. You can adapt the use of ord and chr to your own code, as well as the "wrap-around" math for shift:
def decrypt(s):
shift = int(s[0:2])
time, txt = s.split("/")
txt = txt.replace('_',',-1,').split(",")
print(txt)
txt = (' ' if c=='-1' else chr(ord('a')+(int(c)-shift+26)%26) for c in txt)
return "".join(txt)
print(decrypt("14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1"))
You could also use a character list like ['a','b','c','d'...]
and use positions in the list to get the characters you want.
Upvotes: 0