Python Caesar密码解码

时间:2016-10-24 18:12:46

标签: python python-2.7

我是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()

3 个答案:

答案 0 :(得分:1)

基于你对"你好的评论"作为输入,我怀疑这个问题与不可打印的ascii字符有关。你缺少Caesar密码的两个关键部分。

对于第一个问题,请考虑:

>>> chr(ord(' ') - 4)
'\x1c'

哦不!空格左侧的4个字符(32)是... ASCII文件分隔符! Caesar是如何在粘土片上贴合 的?

关于第二个问题:

>>> chr(ord('A') - 4)
'='

' A'应该在一个真正的凯撒密码中包裹,而是你正在探索非字母ASCII码的腹地(好吧,不是真的)。​​

因此,您需要包含两个重要步骤:

  1. 从Caesar cypher中排除非字母字符。
  2. 确保在接近结尾时字母换行:A - 1应该等于Z

答案 1 :(得分:1)

您可能希望不要解密 {/ 1}}字符,例如加密"加密"文本未加密。如果是这种情况,则以下是代码的修改部分:

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 .page-id-1234 #entry-content { //some css for the page } 将返回原始exec {1}}符号。)

答案 2 :(得分:1)

我的建议是在每个空格中拆分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

注意:

  • 永远不要只在Python 2.x中执行input()因为它隐式使用eval() - 这可能非常危险。请改用int(raw_input())
  • 我删除了您必须创建新行的额外打印语句。而是在第二个打印语句中添加一个新行。