I wrote some code for decoding Vigenère cipher. But it always outputs a wrong decoded message.
And here's my code:
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
v_message= "txm srom vkda gl lzlgzr qpdb? fepb ejac! ubr imn tapludwy mhfbz cza ruxzal wg zztylktoikqq!"
keyword = "friends"
def vigenere_cipher(message, keyword):
decoded = []
for i in range(len(message)):
char = message[i]
if char.isalpha():
char_index = alphabet.index(char)
key_index = alphabet.index(keyword[i % len(keyword)])
letter_index = (char_index - key_index) % len(alphabet)
decoded.append(alphabet[letter_index])
else:
decoded.append(char)
return "".join(decoded)
print(vigenere_cipher(v_message, keyword))
The output it gave me is:
oge fowh ngqx bu hmioua mcaj? xacy zssy! cwa ezk ojhhhaet edsyh lrw ocsish to irplisoxagdn!
And I don't know what's wrong with it. Can anyone help and fix me my code please?
I have asked chatGPT as well but it cannot find the actual error.
You're shifting letters backwards in the alphabet, when you should shift them forwards. This is the opposite of the Vigenere cipher, as pointed out in the comments. So replace
letter_index = (char_index - key_index) % len(alphabet)withletter_index = (char_index + key_index) % len(alphabet)ishould not be incremented for spaces.This will print: