Reputation: 1
Im having trouble with encoding / decoding programming for a vigenere cipher. Im only supposed to use lists, dictionaries and loops. EDIT: I added in the decrypt i have. GetCharList() just gets a list containing the alphabet. I dont know what is wrong that its making the output of the decrpyt not the original message.
def encryptVig(msg, keyword):
alphabet = getCharList() #Get char list is another function which creates a list containing a - z
key = keyword.upper()
keyIndex = 0
dicList = []
for symbol in msg:
num = alphabet.find(key[keyIndex])
if num != -1:
num += alphabet.find(key[keyIndex])
alphabet.find(key[keyIndex])
num%= len(alphabet)
if symbol.isupper():
dicList.append(alphabet[num])
elif symbol.islower():
dicList. append(alphabet[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
dicList.append(symbol)
return " " .join(dicList)
def decryptVig(msg, keyword):
getCharList()
key = keyword.upper()
keyIndex = 0
dicList = []
for symbol in msg:
num = alphabet.find(key[keyIndex])
if num != -1:
num -= alphabet.find(key[keyIndex])
alphabet.find(key[keyIndex])
num%= len(alphabet)
if symbol.isupper():
dicList.append(alphabet[num])
elif symbol.islower():
dicList. append(alphabet[num].lower())
keyIndex -= 1
if keyIndex == len(key):
keyIndex = 0
else:
dicList.append(symbol)
return " " .join(dicList)
Upvotes: 0
Views: 3785
Reputation: 398
Rather than hacking through the alphabet yourself, another approach would be to use ord
and chr
to remove some of the complexity of working with letters. At the very least consider using itertools.cycle
and itertools.izip
to construct a list of the encryption/decryption pairs. Here's how I would solve it:
def letters_to_numbers(str):
return (ord(c) - ord('A') for c in str)
def numbers_to_letters(num_list):
return (chr(x + ord('A')) for x in num_list)
def gen_pairs(msg, keyword):
msg = msg.upper().strip().replace(' ', '')
msg_sequence = letters_to_numbers(msg)
keyword_sequence = itertools.cycle(letters_to_numbers(keyword))
return itertools.izip(msg_sequence, keyword_sequence)
def encrypt_vig(msg, keyword):
out = []
for letter_num, shift_num in gen_pairs(msg, keyword):
shifted = (letter_num + shift_num) % 26
out.append(shifted)
return ' '.join(numbers_to_letters(out))
def decrypt_vig(msg, keyword):
out = []
for letter_num, shift_num in gen_pairs(msg, keyword):
shifted = (letter_num - shift_num) % 26
out.append(shifted)
return ' '.join(numbers_to_letters(out))
msg = 'ATTACK AT DAWN'
keyword = 'LEMON'
print(encrypt_vig(msg, keyword))
print(decrypt_vig(encrypt_vig(msg, keyword), keyword))
>>> L X F O P V E F R N H R
A T T A C K A T D A W N
Upvotes: 2
Reputation: 7923
I don't know how Vigenere is supposed to work. However I am quite sure that after
num = alphabet.find(key[keyIndex])
if num != -1:
num -= alphabet.find(key[keyIndex])
num
is zero.
Upvotes: -1