2014-05-03 41 views
0

Im對vigenere密碼的編碼/解碼編程有問題。我只是應該使用列表,字典和循環。 編輯:我加入瞭解密我有。 GetCharList()只是獲取一個包含字母表的列表。我不知道什麼是錯誤的,它使decrpyt的輸出不是原始消息。Vigenere Cipher Python 2.0

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) 
+0

你有什麼問題? – Schleis

+0

所以基本上我們不能運行你的東西,你有一些問題,但你不告訴我們它是什麼?! – Grapsus

+0

當我編碼時,它會產生一個輸出,例如Q O Q O O Q 當我用解碼功能對它進行解碼時,解碼功能與+進入基本相同 - 反向密碼,它不解密信息。 – SpicehTuna

回答

0

我不知道Vigenere應該如何工作。不過我很確定

num = alphabet.find(key[keyIndex]) 
    if num != -1: 
     num -= alphabet.find(key[keyIndex]) 

num是零。

1

與其自己通過字母黑客入侵,另一種方法是使用ordchr來消除處理字母的一些複雜性。至少考慮使用itertools.cycleitertools.izip來構造加密/解密對的列表。以下是我將如何解決它:

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