【问题标题】:caesar cipher brute force decryption凯撒密码暴力破解
【发布时间】:2013-10-29 22:17:39
【问题描述】:

我正在尝试编写自己的 python 代码来暴力破解凯撒密码,我需要一些帮助。我在函数代码的末尾特别需要帮助。我想知道如何专门打印,以便在每个键尝试后都有一个间隙。我正在使用 python 3.3,并且 3 周前才开始编码。

print ("The plaintext will be stripped of any formatting such as spaces.")
freqlist = []
maxkey = 26
if key > maxkey:
    raise Exception("Enter a key between 0 and 26: ")
elif key < 0:
    raise Exception("Enter a key between 0 and 26: ")
freq = []
inpt=input("Please enter the cipher text:")
inpt = inpt.upper()
inpt = inpt.replace(" ", "")
inpt = inpt.replace(",", "")
inpt = inpt.replace(".", "")
for i in range(0,27):
       key = i

def decrypt():
    for i in range(0,27):
        for a in inpt:
            b=ord(a)
            b-= i
            if b > ord("Z"):
                b -= 26
            elif b < ord("A"):
                b+=26
            freqlist.append(b)
        for a in freqlist:
           d=chr(a)
           freq.append(d)
           freq="".join(freq)
           print(freq.lower(),"\n")
decrypt()

我正在尝试使用 for 循环,但我认为它并不能真正有效地工作。

【问题讨论】:

  • 抱歉,您所说的“有效工作”是指根本不工作(如果是这样,有什么错误消息)或者只是效率不高?这可能是语言问题,但我不明白。
  • 所以现在你有了每个凯撒密码的输入频率表。你打算用这些桌子做什么?你将如何确定哪个密码是正确的?
  • 我只需要有关如何改进此代码的帮助和建议。
  • 这里有一个错误:文件“C:\Users\IshankParul\Desktop\module3.py”,第 29 行,在解密 freq.append(d) UnboundLocalError: local variable 'freq' referenced before assignment

标签: python for-loop python-3.x encryption


【解决方案1】:

根据您发布的错误,我认为这应该会有所帮助。

在 Python 中,您可以拥有同名的局部变量和全局变量。函数中的freq 是本地的,因此全局freq 的初始化不会触及本地。要使用全局freq,您必须通过global statement 告诉函数这样做。这在Python FAQs 中有更多解释。

这应该足以让您重回正轨。

编辑: 以下是对您的 decrypt 函数的编辑,其中包含一些更改说明

def decrypt():

    # we don't need the zero start value, that's the default
    # test all possible shifts
    for i in range(27):

        # initialize the array
        freqlist = []

        # shift all the letters in the input
        for a in inpt:
            b = ord(a)
            b -= i
            if b > ord("Z"):
                b -= 26
            elif b < ord("A"):
                b+=26
            freqlist.append(b)

        # now put the shifted letters back together
        shifted = ""
        for a in freqlist:
           d = chr(a)
           # append the shifted letter onto our output
           shifted += d

        # after we put the decrypted string back together, print it
        # note this is outside the letter loops, 
        # but still inside the possible shifts loop
        # thus printing all possible shifts for the given message
        print(d)

【讨论】:

  • 谢谢。这对我有帮助,但我也在寻找更多可以帮助我展示结果的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
相关资源
最近更新 更多