You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

凯撒密码解密错误求助:Python实现解密结果异常问题

凯撒密码解密失败的问题修复

问题根源

你的加密和解密逻辑中,处理ASCII值超出0-127范围的计算完全错误,没有实现正确的循环映射逻辑,导致加密后的字符无法被反向还原。比如加密时的distance - (127 - ordVal | 1)、解密时的127 - (distance - (ordVal - 1))都是无依据的错误计算,破坏了凯撒密码的偏移对称性。

正确实现思路

凯撒密码的核心是对字符ASCII值偏移后,循环落在0-127的ASCII区间内,最可靠的方式是用模运算(% 128)——因为ASCII共128个字符(0到127),模运算会自动处理超出范围的情况,无需复杂条件判断:

  • 加密:(字符ASCII值 + 偏移量) % 128
  • 解密:(字符ASCII值 - 偏移量) % 128

修正后的代码

加密模块

plainText = input("Enter plain text line: ")
distance = int(input("Enter the distance value: "))
code = ""
for ch in plainText:
    cipherVal = (ord(ch) + distance) % 128
    code += chr(cipherVal)
print(code)

解密模块

code = input("Enter the coded text: ")
distance = int(input("Enter the distance value: "))
plainText = ""
for ch in code:
    cipherVal = (ord(ch) - distance) % 128
    plainText += chr(cipherVal)
print(plainText)

测试验证

用你的测试用例验证:

  • 明文:Hello
  • 偏移量:65
  • 加密结果:*&..0(和你之前的加密结果一致,属于原错误逻辑的巧合)
  • 解密结果:Hello(正确还原原明文)

内容的提问来源于stack exchange,提问作者user2947734

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:45:31