【问题标题】:Beginner Caesar Cipher Decrypt Process for Encryption用于加密的初学者凯撒密码解密过程
【发布时间】:2020-11-08 09:25:54
【问题描述】:

我目前正在学习如何在 Python 中使用凯撒密码方法进行加密/解密。我已经研究过如何加密“14:00/船只就位”以接收“7,21,18,_6,21,22,3,6,_14,5,18,_22,1,_3,2 ,6,22,7,22,2,1' 但我正在为如何编写解密代码而苦苦挣扎。具体来说,我不确定如何使用 if/else 语句正确反转原始加密以及如何将数字转换回字母。每个字母都会根据小时(班次)变化。

解密代码

import string
def decrypt(s):
    s = "14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1"
    shift = int(s[0:2])
    time, plaintext = s.split("/")
    print(shift)
    print(time)
    print(plaintext)
    letters = string.ascii_lowercase
    result = [] 
    for char in plaintext:
        print(char)
        if char == '_':
            result = result + ' '
        else:
            decode = (int(char) - shift) %26
            result = result + str(decode) +','
    print(result)

def main():
    decode = decrypt("14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1")

main()

【问题讨论】:

  • 您需要在, 上拆分您的字符串。现在,您正在迭代数字中的每个数字。您还需要在 _ 上再次拆分,以将 6_14 之类的对分隔为两个字母和一个空格。

标签: python encryption caesar-cipher


【解决方案1】:

您的代码需要的主要内容是用于生成字符的ordchr 函数,以及将shift 转换为负数的原因(使用模数您走在正确的轨道上)。下面的缩短版。您可以根据自己的代码调整 ord 和 chr 的使用,以及 shift 的“环绕”数学:

def decrypt(s):
    shift = int(s[0:2])
    time, txt = s.split("/")
    txt = txt.replace('_',',-1,').split(",")
    print(txt)
    txt = (' ' if c=='-1' else chr(ord('a')+(int(c)-shift+26)%26) for c in txt)
    return "".join(txt)
    
print(decrypt("14:00/7,21,18_6,21,22,3,6_14,5,18_22,1_3,2,6,22,7,22,2,1"))

您还可以使用['a','b','c','d'...] 之类的字符列表,并使用列表中的位置来获取您想要的字符。

【讨论】:

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