逆向工程Ceasar密码

问题描述 投票:3回答:2

我经过反向工程以解密,但未获得预期的结果。

例如,输入

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)
python reverse-engineering
2个回答
0
投票

这是当输入的字符在一定范围内(在这种情况下为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!'

0
投票

[好,我让它适用于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, upper函数中将它们分配给dowork

[lower是对应于您代码中的aupperz

exp是您期望的,exp == got仅检查返回的函数是否正确。一旦您获得正确的功能,它应该适用于[[both我的简单化a-z,2距离,hello测试以及更复杂的4距离,但包括标点符号

上下限

您的2个字符串(输入和输出)是Lipps${svph%Hello World!。这意味着所有这些字符都必须落在您的上下ord值之内,对吗?因此,所有这些交易的最低头寸为您的lower,最大为您的upper。现在,我不是Cryptonomicon的人,我永远不记得ord(a)

最终版本

这不需要您找出将哪个字符置于最低边界而将哪个字符置于上部。我们采用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)

© www.soinside.com 2019 - 2024. All rights reserved.