Currently doing a Vigenere cipher in Python, and me and many people in my class are stuck on one aspect.
After we translated the keyword to ordinals, we need to add those number to a message to encrypt it. This is my code so far.
Input = input('Enter your message: ')
key = input('Enter the one word key: ')
times = len(Input)//len(key)+1
encryptedKey = (times*key)[:len(Input)]
output = []
for character in Input:
number = ord(character) - 96
output.append(number)
outputKey = []
for character in encryptedKey:
numberKey = ord(character) - 96
outputKey.append(numberKey)
print(encryptedKey)
print(outputKey)
print(Input)
print(output)
So if the Input is 'hello'
, and the key is 'bye'
, the keyword would become 'byeby'
[2,25,5,2,25]
, and 'hello'
would be [8,5,12,12,15]
. I can't figure out a way to add the first 2
with 8
, the 25
with 5
, and so on.
I tried print(sum(output + outputKey))
but of course that just adds all the numbers together, meaning the answer is 111
.
I also need them to turn back into letters, so that it ends up with the encrypted message.
Thanks!
You're off to the right start. You've gotten your message and key translated into numbers.
keyphrase = [2,25,5,2,25]
message = [8,5,12,12,15]
Now you need to add them and modulo 26 so your answers are still a-z.
encrypted = [(keyphrase[i] + message[i])%26 for i in range(len(message))]
>>> encrypted
[10, 4, 17, 14, 14]
Now you need to turn those back into letters:
''.join(chr(c + 96) for c in encrypted)
'jdqnn'
And then you can recover the message by going the other way:
message = [(encrypted[i] - keyphrase[i])%26 for i in range(len(encrypted))]
>>> message
[8, 5, 12, 12, 15]
>>> ''.join(chr(c + 96) for c in message)
'hello'
A bit of an FYI, for computer cryptography, especially with a language like Python or C, it's usually standard to start counting at 0. So 'a' is 0, 'b' is 1, etc. You're starting at 1, which is okay, just be aware of it.