Python凯撒密码函数



我想写一个python函数,它可以自动查找任何加密文本的密钥并解密文本。我想使用凯撒密码加密算法。

这个代码是这样的,你会输入rot,但我希望代码能够自动找到rot。

import string
from time import sleep
alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
def decrypt(text, rot):

decrypted_text = "" 
ct = open("rfc8446.txt", "r")
for cipher in text:
if cipher in alphabet:  # check if character is an alphabet

position = alphabet.find(cipher) # find the index position of each text 

new_position = (position - rot) % 25 # find the new index position to decrypt

new_character = alphabet[new_position] # 
decrypted_text += new_character
else:
decrypted_text += cipher
print(decrypted_text)
text = "hnbcnamjh vh krtn unoc vn knqrwm"
rot = 7
decrypt(text, rot)

这将为您提供所有可能的解决方案,只需循环所有旋转即可。

import string
from time import sleep

def decrypt(text):
for rot in range(26):
alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
decrypted_text = ""
for cipher in text:
if cipher in alphabet:
position = alphabet.find(cipher)
new_position = (position - rot) % 25
new_character = alphabet[new_position]
decrypted_text += new_character
else:
decrypted_text += cipher
print(decrypted_text)

text = "hnbcnamjh vh krtn unoc vn knqrwm"
decrypt(text)

然而,找到好的解决方案要复杂得多,因为你需要确定哪种解决方案";外观;英语,使用文本合理性矩阵之类的东西