gpt4 book ai didi

python - 逆向工程凯撒密码

转载 作者:行者123 更新时间:2023-12-02 06:38:24 26 4
gpt4 key购买 nike

我进行了逆向解密,但没有得到预期的结果。

例如,输入

Lipps${svph%

偏移量 4 应该导致

Hello World!

但我明白了

ello´world³

我做错了什么?

code = input("Enter text to decrypt: ")
distance = int(input("Enter number of offset: "))
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)

最佳答案

好的,我让它适用于 a-z 并为您提供了一个小测试框架来自动输入/检查,而不是每次都输入。

def dowork(code, distance, lower, upper):


bounddown, boundup = ord(lower), ord(upper)

plaintext = ""
for ch in code:
ordValue = ord(ch)
cipherValue = ordValue - distance
if cipherValue < bounddown:
cipherValue = boundup - bounddown - ordValue +1

plaintext += chr(cipherValue)


return plaintext

dataexp = [
(("jgnnq",2, 'a', 'z'),"hello"),
]

for input_, exp in dataexp:
got = dowork(*input_)
msg = "exp:%s:%s:got for %s" % (exp, got, inp)
if exp == got:
print("good! %s" % msg)
else:
print("bad ! %s" % msg)

这会打印

good! exp:hello:hello:got for ('jgnnq', 2, 'a', 'z')

现在您需要做的就是向 dataexp 列表中添加一个额外的项目,例如

(("Lipps${svph%", 4, <lowerbound>, <upperbound char>), "Hello World!")

一旦你弄清楚了上限和下限,它就应该可以工作。请注意,我不知道凯撒代码,我只是直接复制了你的代码,但对其进行了一些重组。

什么*_input所做的就是获取该元组(或多或少是一个列表)中的这 4 个值并将它们分配给 code, distance, lower, upperdowork功能。

lower对应于a在你的代码和 upperz .

exp 是您所期望的并且 exp == got只是检查函数返回的内容是否正确。一旦你得到正确的函数,它应该适用于两者我的简单化 a-z , 2 距离, hello测试和更复杂的 4 距离,但包括标点符号

下限和上限

您的 2 个字符串(输入和输出)是 Lipps${svph%Hello World! 。这意味着所有这些字符都需要落在您的上限和下限值内,对吧?所以所有这些的最小顺序位置是你的 lower最大值是你的 upper 。现在,我不是密码学里的那个人,我不记得是否 ord(a) < ord(A) ,更不用说标点符号了。所以你必须对此进行修改,这就是为什么我只基于小写字母进行测试。不过我会添加 0-9。

最终版本

这不需要您弄清楚将哪个字符放在最低边界以及将哪个字符放在上限。我们采用 lower = 32(可打印字符的开头),upper = 255。这样标点符号、大小写、数字及其 ord 值就不再重要了。

#full ASCII range, you can go to town on entering whatever you want
bounddown, boundup = 32, 255

plaintext = ""
for ch in code:
ordValue = ord(ch)
cipherValue = ordValue - distance
if cipherValue < bounddown:
cipherValue = boundup - bounddown - ordValue +1

plaintext += chr(cipherValue)

关于python - 逆向工程凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60795235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com