[英]Python Caesar cipher decoding
我是Python的新手,因此決定制作自己的Caesar密碼加密器。 我已經做了加密器,沒關系,但是解密器只能成功解密一個字。 如果我輸入一個句子,它將解密全部合並在一起。 有一個簡單的解決辦法嗎?
def decrypt():
ciphertext = raw_input('Please enter your Encrypted sentence here:')
shift = input('Please enter its shift value: ')
space = []
cipher_ords = [ord(x) for x in ciphertext]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
print 'Decryption Successful'
print ""
print 'Your encrypted sentence is:', plaintext
decrypt()
根據您對“ hello there”作為輸入的評論,我懷疑此問題與不可打印的ascii字符有關。 您缺少凱撒密碼的兩個關鍵部分。
對於第一個問題,請考慮:
>>> chr(ord(' ') - 4)
'\x1c'
不好了! 空格( 32
)左邊的4個字符是... ASCII文件分隔符! 凱撒如何將它放在黏土板上?
對於第二期:
>>> chr(ord('A') - 4)
'='
'A'應該包裹在一個真正的凱撒密碼中,但是相反,您正在探索非字母ASCII碼的腹地(不是,實際上)。
因此,您需要包括兩個重要步驟:
A - 1
應該等於Z
您可能不希望不對 space
字符進行解密 ,因為未加密的 “加密”文本中的字符。 在這種情況下,這是代碼的修改部分:
cipher_ords = [ord(x) if x != " " else -1 for x in ciphertext]
plaintext_ords = [o - shift if o != -1 else -1 for o in cipher_ords]
plaintext_chars = [chr(i) if i != -1 else " " for i in plaintext_ords]
(對於每個空格符號,讓cipher_ords
也具有-1
,因此,在plaintext_ords
中也是如此。在plaintext_chars
此-1
將返回到原始space
符號。)
我建議的是在每個空格處拆分raw_input()
,遍歷拆分輸入中的每個單詞,然后將句子與空格一起返回。 這似乎是我能想到的最經典的解決方案:
def decrypt():
ciphertext = raw_input('Please enter your Encrypted sentence here:')
shift = int(raw_input('Please enter its shift value: '))
space = []
# creat a list of encrypted words.
ciphertext = ciphertext.split()
# creat a list to hold decrypted words.
sentence = []
for word in ciphertext:
cipher_ords = [ord(x) for x in word]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
sentence.append(plaintext)
# join each word in the sentence list back together by a space.
sentence = ' '.join(sentence)
print 'Decryption Successful\n'
print 'Your encrypted sentence is:', sentence
decrypt()
輸出:
Please enter your Encrypted sentence here: lipps xlivi
Please enter its shift value: 4
Decryption Successful
Your encrypted sentence is: hello there
筆記:
input()
,因為它隱式使用了eval()
,這可能非常危險。 使用int(raw_input())
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.