ntl_ps = [ # -> normal_text_letter_probabilitys
0.082,
0.015,
0.028,
0.043,
0.127,
0.022,
0.02,
0.061,
0.07,
0.002,
0.008,
0.04,
0.024,
0.067,
0.015,
0.019,
0.001,
0.06,
0.063,
0.091,
0.028,
0.01,
0.024,
0.002,
0.02,
0.001
]
def cipher_break(ciphertext):
cpt_ls = [0 for i in range(0, 26)] # -> ciphertext_letter_statistics
for c in ciphertext:
cpt_ls[ord(c) - 65] += 1
cpt_len = len(ciphertext)
cpt_ps = [n/cpt_len for n in cpt_ls] # -> ciphertext_probabilitys_for_its_letter
I_js = [abs(sum([cpt_ps[i] * ntl_ps[(i + j) % 26] for i in range(26)]) - 0.065) for j in range(26)]
return I_js.index(min(I_js))
def dec_test(ciphertext, k):
m = ''
for c in ciphertext:
m += chr((ord(c) - 65 + k) % 26 + 65)
return m
if __name__ == '__main__':
cipher_text = 'OVDTHUFWVZZPISLRLFZHYLAOLYL'
print(dec_test(cipher_text, cipher_break(cipher_text)))
密码学基础第一次课编程作业——破译移位密码
于 2022-09-20 08:51:46 首次发布