Reputation: 1346
For fun, I am trying to run a caesar cipher on a string where each character is shifted by the previous character in the string. The initial character is obviously not shifted and used to shift the second, the second character is used as the seed for the third character, etc
Encoding appears to be working as intended; decoding on the other hand...
key = "a"
word = key + "shop"
print(word)
coded = ""
for i, val in enumerate(word[1:]):
coded += (chr(((ord(word[i]) + ord(val) - 97) % 26) + 97))
print(key + coded)
encoded = key + coded
decoded = ""
for i, val in enumerate(encoded[1:]):
decoded += chr(((ord(encoded[i]) - ord(val) - 97) % 26) + 97)
print(key + decoded)
My Maths appears (to the naive eye) correct. Does the encoding have some property that I am not aware of that does not allow for reversing of this?
Example output using the inputs above:
ashop
alsow
amqbp
Obviously I would like the amqbp
to be ashop
. Moving the -97 around does not help (not even sure why it would if it did).
What am I missing here?
Upvotes: 2
Views: 68
Reputation: 40703
Your encoding loop appears to be incorrect. I would expect S shifted by A to be T. But your output is L. Maybe try encoding za
, which should result in za
to see where you might be going wrong. As a guess, it looks like the problem is that you are taking the modulus of the character code and not the characters index in the alphabet. Eg. For a
you end up doing 97 % 26
instead of 0 % 26
.
Upvotes: 1