Python:解密凯撒密码

标签 python encryption caesar-cipher

作业:

编写一个脚本,输入一行加密文本和一个距离值,并使用凯撒密码输出明文。

我的问题:

正在打印 hello^3 world^2

我不太清楚为什么。我将不胜感激任何修复或理解我的代码中的错误的帮助。 (这不是为成绩分配的,即没有截止日期为了我自己的利益而做)

它希望我能够使用其各自的输入:

利普斯${svph% 4

Jhss'tl'Pzothls5 7

Zu&hk2&ux&tuz&zu&hk 2

khoor#zruog$ 3

我的代码:

code = input("enter coded text: ") 
distance = int(input("enter value: ")) 
plainText = "" 
for ch in code: 
  ordvalue = ord(ch) 
  ciphervalue = ordvalue - distance 
  if ciphervalue < ord('a'): 
    ciphervalue = ord('z') - \
      (distance - (ord('a')-ordvalue - 1))
  plainText += chr(ciphervalue) 
print(plainText)

最佳答案

首先,您应该将输入/输出与处理分离,因为您的代码将更容易测试:

def cipher(code, distance):
    plainText = ""
    for ch in code:
        ordvalue = ord(ch)
        ciphervalue = ordvalue - distance
        if ciphervalue < ord('a'):
            ciphervalue = ord('z') - (distance - (ord('a')-ordvalue - 1))
        plainText += chr(ciphervalue)
    return plainText

code = input("enter coded text: ")
distance = int(input("enter value: "))
print(cipher(code, distance))

现在,您拥有:

>>> cipher("Lipps${svph%", 4)
'\x8aello²world±'

我猜您期待的是“Hello world!”之类的内容。如果删除这两行,就会得到以下结果:

if ciphervalue < ord('a'):
    ciphervalue = ord('z') - (distance - (ord('a')-ordvalue - 1))

看:

def cipher2(code, distance):
    plainText = ""
    for ch in code:
        ordvalue = ord(ch)
        ciphervalue = ordvalue - distance
        plainText += chr(ciphervalue)
    return plainText

>>> cipher2("Lipps${svph%", 4)
'Hello world!'
>>> cipher2("Jhss'tl'Pzothls5", 7)
'Call me Ishmael.'
>>> cipher2("Zu&hk2&ux&tuz&zu&hk", 6) # was 2, but I guess it's 6
'To be, or not to be'
>>> cipher2("khoor#zruog$", 3)
'hello world!'

这是这个问题有趣的部分。但我认为您有正确的直觉:当生成的ordvalue 值不在预期范围内(即负值或过大)时会发生什么?

>>> cipher2("hello", 103)
Traceback (most recent call last):
...
ValueError: chr() arg not in range(0x110000)

函数 ord 生成一个 0 到 1114111 之间的 unicode 代码点,但我认为对于练习,您可以将范围限制为 0 - 127(ASCII 字符):

def cipher3(code, distance):
    assert abs(distance) < 128
    plainText = ""
    for ch in code:
        ordvalue = ord(ch)
        ciphervalue = ordvalue - distance
        if ciphervalue < 0:
            ciphervalue += 128
        elif ciphervalue >= 128: # don't forget distance can be negative
            ciphervalue -= 128
        plainText += chr(ciphervalue)
    return plainText

>>> cipher3("hello", 103)
'\\x01~\\x05\\x05\\x08'
>>> cipher3('\x01~\x05\x05\x08', -103)
'hello'

请注意:

        if ciphervalue < 0:
            ciphervalue += 128
        elif ciphervalue >= 128: # don't forget distance can be negative
            ciphervalue -= 128

相当于:

        ciphervalue = ciphervalue % 128

如果您只想使用可打印字符,您可以使用string模块:

import string
# string.printable is '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

def cipher4(code, distance):
    assert abs(distance) < len(string.printable)
    plainText = ""
    for ch in code:
        ordvalue = string.printable.index(ch) # this is clearly suboptimal
        ciphervalue = (ordvalue - distance) % len(string.printable)
        plainText += string.printable[ciphervalue]
    return plainText

>>> cipher4("hello", 80)
'ByFFI'
>>> cipher4('ByFFI', -80)
'hello'

关于Python:解密凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103130/

相关文章:

python - 为每个 numpy 列分配不同的权重

python - 如何在不卸载的情况下使用多个版本的Python

Java:凯撒密码不会打印

amazon-web-services - 如何保护传输中的 AWS S3 上传/下载数据?

java - 尝试使用 if 语句制作加密方法

c - 我的凯撒密码版本有什么问题?参数组2

python - 图表上的烦人日期

python - 使我的 pypi 脚本可执行,而无需每次都指定脚本的路径

encryption - 更改由 AES CBC 加密的文件中的 1 个字节会导致它无法再解密吗?

C++凯撒密码程序执行错误的字符