2017-09-25 52 views
0

我必須使用Caesar Cipher加密用戶提供的明文。將每個純文本字符轉換爲其ASCII(整數)值並存儲在列表中。 我曾經做過這樣的Python中的凱撒密碼(意外錯誤)

print("This program uses a Caesar Cipher to encrypt a plaintext message using the encryption key you provide.") 
plaintext = input("Enter the message to be encrypted:") 
plaintext = plaintext.upper() 
n = eval(input("Enter an integer for an encrytion key:")) 
ascii_list = [] 

# encipher 
ciphertext = "" 
for x in range(len(plaintext)): 
    ascii_list[x] = plaintext (ascii_list) + n %26 
    print() 

但是像這樣出現錯誤:

TypeError: 'str' object is not callable 

我想要的結果出來:

This program uses a Caesar Cipher to encrypt a plaintext message using the encryption key you provide. 
Enter the message to be encrypted: Boiler Up Baby! 
Enter an integer for an encrytion key: 1868 
The fully encoded message is: CWOTFZ&]QCHICa' 

我已經嘗試了很多不同的方式,但結果不出來。

+3

你期望'純文本(ascii_list)'做什麼? –

回答

1

您需要將初始字符解析爲數字,然後向其中添加密鑰,然後將其解析回字符。

在您的代碼中ascii_list[x]必須更改爲ascii_list.append(),因爲您引用的索引不存在。另外plaintext不是您可以調用的函數,它只是您的大寫初始消息。

你可以這樣做:

for x in range(len(plaintext)): 
    ascii_list.append(chr(ord(plaintext[x]) + n)) 
print(ascii_list) 

注: 輸入/輸出(在:Boiler Up Baby!,出:CWOTFZ&]QCHICa')你提供的是不典型的愷撒密碼的一些字母變成符號,符號也被編碼。使用這種解決方案只會將鍵移開,這意味着例如Z將永遠不會變成A。如果你需要適當的凱撒密碼解決方案,你可能想看看這個問題:Caesar Cipher Function in Python