def caesar_encrypt(message, key): """ 凯撒加密函数 :param message: 明文 :param key: 秘钥,整数类型,表示向右移动的位数 :return: 密文 """ ciphertext = "" for char in message: if char.isalpha(): shift = key % 26 if char.islower(): ciphertext += chr((ord(char) - 97 + shift) % 26 + 97) else: ciphertext += chr((ord(char) - 65 + shift) % 26 + 65) else: ciphertext += char return ciphertext

def frequency_analysis(ciphertext): """ 频率统计函数 :param ciphertext: 密文 :return: 字母频率字典 """ freq_dict = {} for char in ciphertext: if char.isalpha(): if char in freq_dict: freq_dict[char] += 1 else: freq_dict[char] = 1 total_count = sum(freq_dict.values()) for char, count in freq_dict.items(): freq_dict[char] = count / total_count return freq_dict

def caesar_decrypt(ciphertext, key): """ 凯撒解密函数 :param ciphertext: 密文 :param key: 秘钥,整数类型,表示向右移动的位数 :return: 明文 """ plaintext = "" for char in ciphertext: if char.isalpha(): shift = key % 26 if char.islower(): plaintext += chr((ord(char) - 97 - shift + 26) % 26 + 97) else: plaintext += chr((ord(char) - 65 - shift + 26) % 26 + 65) else: plaintext += char return plaintext

def caesar_crack(ciphertext): """ 凯撒破解函数 :param ciphertext: 密文 :return: 明文和秘钥 """ freq_dict = frequency_analysis(ciphertext) freq_list = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True) most_common_char = freq_list[0][0] key = ord(most_common_char) - ord('e') return caesar_decrypt(ciphertext, key), key

def main(): message = "Hello, World!" key = 3 ciphertext = caesar_encrypt(message, key) print("密文:", ciphertext) freq_dict = frequency_analysis(ciphertext) print("字母频率统计:", freq_dict) plaintext, key = caesar_crack(ciphertext) print("破解出的秘钥:", key) print("明文:", plaintext)

if name == 'main': main(

如何使用python实现1实现凯撒加密将明文M加密成密文C2利用频率统计密文C的频率3从频率统计中找出凯撒加密的秘钥K4利用秘钥K破解凯撒加密把所有代码总合成函数输出

原文地址: http://www.cveoy.top/t/topic/fer5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录