Writing a Caesar and Vigenere cipher.
I have the code working correctly (I think).
My concern with the code, where there are spaces in the text. I need the key to pick up, move over the space, and return when there is another character...
Ex: $ python vigenere.py
Type a message:
'The crow flies at midnight!'
Encryption key: boom
Correct output: Uvs osck rmwse bh auebwsih!
output I receive:
uvs drow tzufs mu muenwsit
You can see after the first word the sequence is lost, because it applies the m key to a space that does not have a character present... I hope this makes sense.
Here is my code. I put in line 30 to try and correct this issue, but it did not help. (if letter in text == ' ': starting_index = starting_index - 1)
import string
def alphabet_position(letter):
if letter.isupper():
letter = ord(letter) - 65
else:
letter = ord(letter) - 97
return letter
def rotate_character(char, rot):
alpha = 'abcdefghijklmnopqrstuvwxyz'
new = alphabet_position(char) + rot
if char.isupper():
if new < 26:
new = new + 65
return chr(new)
elif new < 0 :
return char
elif new >= 26:
return char
else:
new = new + 97
return chr(new)
def encrypt(text, key):
alpha = ['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']
encrypted = []
starting_index = 0
for letter in text:
if letter in text == ' ':
starting_index = starting_index - 1
rotation = alphabet_position(key[starting_index])
if not letter in alpha:
encrypted.append(letter)
elif letter.isalpha():
encrypted.append(rotate_character(letter, rotation))
if starting_index == (len(key) - 1):
starting_index = 0
else:
starting_index += 1
return ''.join(encrypted)