Viginere密码破解(For循环问题)

时间:2018-11-28 17:16:40

标签: python-3.x for-loop

因此,我正在编写一些与打破viginere密码有关的代码,但是由于某种原因,如果我在运行代码而没有k的外部循环的情况下运行了这个循环,那么我就在那儿,而这个循环还是很狡猾的获得卡方的正确值。但是,一旦我将循环中的值设置为不正确,就不确定我做错了什么,那么一些指导将是王牌。

最小值应该是k = 19时。

代码在这里:

import string
alphabet = string.ascii_lowercase

exp_values = [0.0815, 0.0137, 0.0221, 0.0458, 0.1261, 0.0186, 0.0236,0.0685,
            0.0697, 0.0014, 0.0107, 0.0437, 0.0196,   0.0652, 0.0758, 0.014,
            0.0019, 0.0502, 0.0605, 0.0993, 0.0322,   0.0078, 0.0249, 0.0013, 0.0211,
            0.0007]


def chi_square(obs,exp):
    sum = 0
    for i in range(0,len(obs)):
        sum = sum + ( obs[i]- exp[i] )**2 / exp[i]
    return sum

plain = 'blxiiftelbmklwixafhxblipaxaxyvhtpuvrahwdnemvbmofytpxhzxmmwvpmxxxpnowxkhxuaxt'

for k in range(1,25):
    ctext = ''
    for i in plain:
        x = ((ord(i) - 65) + k) % 26
        ctext = ctext + chr(x + 65)
    ctext = ctext.lower()

    freqs = {}
    # Get the count of each letter
    for i in alphabet:
        count = ctext.count(i)
        if count == 0:
            freqs[i] = 0
        else:
            freqs[i] = count

    # Turn the frequency into probabilities
    obs_values = []
    for i in alphabet:
        a = freqs.get(i)/len(ctext)
        obs_values.append(a)

    print('Key =', k,' ', chi_square(obs_values,exp_values))

0 个答案:

没有答案