Python-Caesar密码解码
我是Python新手,决定自己制作凯撒密码加密机。我已经做了加密程序,它是好的,但是,解密程序只能成功地解密一个字。如果我输入一个句子,它会将解密合并在一起。有没有简单的解决办法Python-Caesar密码解码,python,python-2.7,Python,Python 2.7,我是Python新手,决定自己制作凯撒密码加密机。我已经做了加密程序,它是好的,但是,解密程序只能成功地解密一个字。如果我输入一个句子,它会将解密合并在一起。有没有简单的解决办法 def decrypt(): ciphertext = raw_input('Please enter your Encrypted sentence here:') shift = input('Please enter its shift value: ') space = []
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'
哦,不!空格左边的4个字符(32
)是…ASCII文件分隔符!凯撒是怎么把它放在泥板上的
第二期:
>>> chr(ord('A') - 4)
'='
“A”应该是真正的凯撒密码,但是你要探索的是非字母ASCII码的腹地(嗯,不是真的)
因此,您需要包括两个重要步骤:
A-1
应等于Z
空格
字符,因为在您的“加密”文本中它没有加密。如果是这种情况,下面是代码的修改部分:
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]
(让
密码
为每个空格符号和明文
中的顺序设置-1
。在明文
中,此-1
将返回原始空格
符号)。我建议在每个空格拆分原始输入(),迭代分割输入中的每个单词,然后用空格将句子连接起来。这似乎是我能想到的最规范的解决方案:
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
注:
- 永远不要在Python2.x中只执行
input()
,因为它隐式地使用eval()
,这可能非常危险。使用int(原始输入())
- 我删除了额外的打印语句,您必须创建一个新行。改为在第二个print语句中追加一行
您确定问题不是从您的加密机开始的吗?您的代码在这里看起来正常。您能为is提供输入和预期输出吗?此外,您不应该使用input
,因为这允许执行任意代码。而是执行int(原始输入())
。否,因为它是一个单独的文件。我只是简单地输入“lipps xlivi”,并将其转换为“hello there”。但是,我用当前代码得到了“hellothere”。@MatthewWillis您的加密文本没有“空格”字符移位。要么把它和你的百科全书的一部分转移,要么让你的解密程序不要试图“取消”空间的转移,那么我该怎么做呢?