我反向工程解密,但没有得到预期的结果。
例如,输入
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)发布于 2020-03-22 04:30:11
好的,我让它工作在a,并给您一个小的测试框架,以自动进入/检查,而不是每次输入它。
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个值(或多或少是一个列表),并将它们分配给dowork函数中的code, distance, lower, upper。
lower对应于代码中的a,upper对应于z。
exp是您所期望的,exp == got只检查返回的函数是否正确。一旦你得到正确的函数,它应该适用于,-我简化的a-z,2距离,hello测试和你更复杂的4距离,但包括标点符号
上下界
您的两个字符串,输入和输出,是Lipps${svph%和Hello World!。这意味着所有这些字符都必须属于您的上、下ord值,对吗?因此,所有这些的最小ord位置是您的lower,最大值是您的upper。现在,我不是隐眼压图标的人,我永远也不记得ord(a) < ord(A)是否存在,更不用说标点符号了。所以你必须对此做些修正,这就是为什么我的测试只以小写字母为基础。不过,我要加0-9。
最终版本
这不需要你去弄清楚哪个字符应该放在最低的范围里,哪个在上面。我们取小写= 32 (可打印字符的开始),上部= 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)发布于 2020-03-22 05:08:29
下面是一个实现,用于在一定范围内(在本例中为a-z)输入字符时进行加密和解密。您可以根据需要对其他范围进行调整。
def caesar(text, offset, decrypt=False):
lower_bound, upper_bound = ord('a'), ord('z')
if decrypt:
offset = (upper_bound - lower_bound + 1) - offset
result = ''
for t in text:
o = ord(t)
if lower_bound <= o <= upper_bound:
new_t = o + offset
if new_t > upper_bound:
new_t = (new_t % upper_bound) + lower_bound - 1
result += chr(new_t)
else:
result += t
return result然后你可以打电话:
caesar(caesar('hello world!', 2,), 2, True)
# => 'hello world!'https://stackoverflow.com/questions/60795235
复制相似问题