1

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)
Blorgbeard
  • 93,378
  • 43
  • 217
  • 263
  • It would seem that by not encryption the spaces (and punctuation) you leak a lot of information and make the encryption easy to break. – zaph Aug 29 '17 at 16:34
  • I agree, However this was part of an assignment. – Anoushir Mansouri Aug 29 '17 at 17:00
  • Please fix the indentation of your code, it's hard to read as is. Your fix would work, but it should be `letter == ' '`. However, it only handles spaces, not other punctuation. I'll leave it to you to figure out how to handle those in the general case – c2huc2hu Aug 29 '17 at 17:36

0 Answers0