【问题标题】:Using caesar cipher to decrypt ciphertext使用凯撒密码解密密文
【发布时间】:2015-03-17 15:19:37
【问题描述】:

我正在尝试使用此代码将密文 "htrgti" 解密为纯文本。我不断收到 "wigvix" 这不是我应该收到的信息。

鉴于纯文本(应该是常用词或短语)和键,对于说 ciphertext 的每个位置,我将其替换为 plaintext,并且对于每个说 plaintext 的位置都相同:

def caesar(ciphertext, shift):  
    alphabet=["a","b","c","d","e","f","g","h","i",
              "j","k","l","m","n","o","p","q","r",
              "s","t","u","v","w","x","y","z"]  
    plaintext = ""

    for i in range(len(ciphertext)):                        
        letter = ciphertext[i]                  

        # Find the number position of the ith letter
        num_in_alphabet = alphabet.index(letter)        

        # Find the number position of the cipher by adding the shift    
        plain_num = (num_in_alphabet + shift) % len(alphabet)   

        # Find the plain letter for the cipher number you computed
        plain_letter = alphabet[plain_num]          

        # Add the cipher letter to the plaintext
        plaintext = plaintext + plain_letter            

    return plaintext

【问题讨论】:

  • 想想用 dict 和 str.translate 来做这件事是多么容易!
  • 如果您使用N 的移位进行编码,您将使用alphabet_len - N 的移位进行解码。您目前使用什么班次值?
  • 另外,顺便说一句,字符串在 Python 中是可迭代的,因此无需将字母表显式设为列表。它也已作为string.ascii_lowercase 提供。
  • 我使用的移位值是 15
  • 这是教授的作业,让你每行都评论吗?

标签: python python-3.x


【解决方案1】:

如@Mr.Llama 所暗示的那样,如果你正确调用它,你的函数就会起作用,右移caesar("htrgti", 11)secret。您的函数本身运行正常。这是您的代码的更好版本,但仍然存在每个.index 查找都是 O(alphalen) 的问题。因此,作为奖励,我添加了 @Two-Bit Alchemist 建议的实现以使用 str.translate。

import string
alphabet = string.ascii_lowercase
alphalen = len(alphabet)
shift = 11

def caesar(ciphertext, shift):  
    plaintext = ""
    for letter in ciphertext:
        num_in_alphabet = alphabet.index(letter)        
        plain_num = (num_in_alphabet + shift)  %  alphalen
        plain_letter = alphabet[plain_num]          
        plaintext = plaintext + plain_letter            
    return plaintext

print(caesar("htrgti", shift))
# secret

table = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
print("htrgti".translate(table))
# secret

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2014-03-07
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多