It looks like your offsetD
value has the wrong sign (or you need to be subtracting it, rather than adding). If it is positive 93, you'll get the output you show in your example run. Either change how its value is set (e.g. offsetD = -int(input("Please enter offset value (1 to 94):"))
or subtract the value when you go to use it (e.g. decryption -= offsetD
).
Python Caeser Cypher - Wrap back to beginning
-
18-07-2023 - |
Question
A small problem with the Caeser Cypher program I'm writing. I'm new to programming.
So, when the offset points to a character past 126 I want to wrap back to the beginning, so that it works with the ASCII character set. I've managed to do that while encrypting like this:
if encryption > 126:
encryption = encryption - 94
Which works fine. But while decrypting, it doesn't seem to work. I'm still getting characters that are outside of the ASCII character set. E.g:
Please enter string to decrypt: abcdefg
Please enter offset value (1 to 94): 93
Decrypted string:
¾¿ÀÁÂÃÄ
Here is the code I've written:
for letter in range(len(messageD)):
decryption = ord(messageD[letter])
decryption += offsetD
if decryption < 32:
decryption = decryption + 94
decryption = chr(decryption)
decryptedD += decryption
print('Decrypted string:\n', decryptedD)
If the subtracted offset results in a number less than 32, we're supposed to add 94 to the result. I thought that is exactly what I've done here, but I must be going wrong somewhere.
It's also not decrypting strings properly. I can encrypt strings, but when I try to decrypt the string I just encrypted, it returns the wrong result.
Any help would be greatly appreciated :) Thanks in advance.
Solution