Caesar密码环绕法,用于更容易混淆的ASCII字符

2024-10-02 22:29:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我了解凯撒密码方法,并成功地使用模运算符编写了我自己的概括,但我不了解我正式学习课本中所示的方法。我指的是我在下面评论的代码:

plainText = input("Enter a one-word, lowercase message: ")
distance = int(input("Enter the distance value: "))
code = ""
for ch in plainText:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    #confusion begins here
    if cipherValue > ord('z'):
        cipherValue = ord('a') + distance - \
            (ord('z') - ordvalue + 1)
    #confusion ends here
    code += chr(cipherValue)
print(code)

Tags: 方法密码inputherecode运算符chdistance
1条回答
网友
1楼 · 发布于 2024-10-02 22:29:24

如果你想一想,它是有意义的,即使它是一个稍微冗长和复杂的计算方法。唉,表达的复杂程度没有限制,只有表达的简单程度

所以ord('a')ord('z')的值是97和122。当我们得到ord(char) + distance = 123,时,我们想把它映射回ord('a'),对吧。所以我们需要减去允许的字符间隔的长度。此间隔的大小为ord('z') - ord('a') + 1(+1,因为两个端点实际上都是间隔和允许值的一部分)

结果公式为(假设ordValue + distance > ord('z')

cipherValue = ordValue + distance - (ord('z') - ord('a') + 1) 
            = ordValue + distance - ord('z') + ord('a') - 1
            = ord('a') + distance - ord('z') + ordValue - 1
            = ord('a') + distance - (ord('z') - ordValue + 1)

。。。这是让你困惑的表达

最后,此方法存在一个陷阱,即它最多只覆盖ord('z') - ord('a') + 1的溢出,因此如果distance比这长,它将无法工作:

cipherValue = ordValue + distance - (ord('z') - ord('a') + 1) 
            = ordValue + (ord('z') - ord('a') + 2) - ord('z') + ord('a') - 1
            = ordValue + ord('z') - ord('a') + 2 - ord('z') + ord('a') - 1
            = ordValue + 1

现在,如果ordValue来自ord('z'),那么我们就有麻烦了,因为密码值将是ord('z') + 1 = 123,它与密文字母表中的字符(chr(123) = '{')不对应

也许我们可以假设distance不应该那么长或更长(这是有道理的),否则使用模表达式会更安全

相关问题 更多 >