2015-11-18 51 views
1

我一直在編碼Vigenere密碼,但程序在回到第26個字母z之前回轉。如果值是122,而不是打印z,或者甚至可以是a,那麼它就是第96個ASCII字符 - '。Vigenere密碼,循環之前122/z

這是我的代碼:

def getMode(): 
    while True: 
     mode = input("enter encrypt, e, decrypt or d: ") 
     if mode in 'encrypt e decrypt d ENCRYPT E DECRYPT D Encrypt Decrypt'.split(): 
      return mode 
     else: 
      input('Please enter encrypt or decrypt to start: ') 

mode = getMode() 
message = input('Enter your message: ') 
for char in ' ?.,:;-!/': 
    message = message.replace(char,'') 
key = input('Enter the one word key: ') 
times = len(message)//len(key)+1 
encryptedKey = (times*key)[:len(message)] 

output = [] 
for character in message: 
    number = ord(character) - 96 
    output.append(number) 

outputKey = [] 
for character in encryptedKey: 
    numberKey = ord(character) - 96 
    outputKey.append(numberKey) 

if mode[0] == 'd': 
    outputKey = [-x for x in outputKey] 

encryptedMessage = [(outputKey[i] + output[i])%26 for i in range(len(output))] 
finalMessage = ''.join(chr(c + 96) for c in encryptedMessage) 

print(message) 
print(encryptedKey) 
print(outputKey) 
print(output) 
print(encryptedMessage) 
print('Your encrypted message is: ' + finalMessage) 

基本上,如果我輸入:

enter encrypt, e, decrypt or d: e 
Enter your message: abcdefghijklmnopqrstuvwxyz 
Enter the one word key: yo 
abcdefghijklmnopqrstuvwxyz 
yoyoyoyoyoyoyoyoyoyoyoyoyo 
[25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15] 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] 
[0, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 1, 12, 3, 14, 5, 16, 7, 18, 9, 20, 11, 22, 13, 24, 15] 
Your encrypted message is: `qbsdufwhyjalcnepgritkvmxo 

應該是Z,26號,現在是',我不知道什麼我我們已經儘早完成了這個循環。

這是一個小問題,但可以真的搞砸了消息。任何幫助表示讚賞 - 如果有這樣的問題(雖然我找不到),請重定向到它!

謝謝!

+0

「對不起,我真的不知道如何讓文本看起來像塊代碼」 - 縮進四個或更多字符。 – rossum

回答

0

你的問題是26%26是0而不是26!因此而不是z(chr(96 + 26)),你會得到一個`(chr(96 + 0))。

您可以輕鬆修復它,但可以在encrypted_message計算機中逐步修復。 :

encryptedMessage = [(outputKey[i] + output[i] - 1)%26 + 1 for i in range(len(output))] 

然後,您將得到正確的:

[25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15] 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] 
[26, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 1, 12, 3, 14, 5, 16, 7, 18, 9, 20, 11, 22, 13, 24, 15] 
Your encrypted message is: zqbsdufwhyjalcnepgritkvmxo 
0

在ASCII '一' 是97 你的第一個字符是0 + 96這樣 ''' 而不是 '一'。

在加密'a'時,使用嚴格的Vigenere密碼時,它應該成爲關聯的關鍵字(沒有'a'的轉換)。 在您爲例「A」變成0,而不是25

我想你應該訂購你的信從0到25,而不是1到26,即使用97而不是96

所以你會得到數字在0到25之間。一旦你添加了97,你就會得到你的字母從'a'到'z'。

希望我的回答沒有大的錯誤。如果是的話,我會編輯或刪除,如果需要。 ;-)