我们可以写一个函数进行暴力破解凯撒密码。具体方法是从1到25枚举凯撒密码的密钥,每个密钥用来解密密文,并判断解密后的明文是否符合语句中的一些常见单词和短语,例如“the”、“and”、“of”等等。如果符合,就输出解密后的明文和密钥。以下是Python代码示例:
def brute_force(cipher_text):
""" Bruteforcing the Caesar cipher """
# English common words and phrases for checking plaintext
common_words = ["the", "and", "of", "to", "in", "that", "with", "is", "for", "it", "on", "at", "by", "this", "we", "you", "not", "be", "are"]
# Brute force the cipher key by enumerating from 1 to 25
for key in range(1, 26):
plain_text = ""
# Decrypt the cipher text with current key
for c in cipher_text:
if c.isalpha():
# Shift the character back by key positions
shifted_c = ord(c)-key
if shifted_c < 65:
shifted_c += 26
plain_text += chr(shifted_c)
else:
plain_text += c
# Check if the decrypted plaintext contains common words and phrases
for word in common_words:
if word in plain_text.lower().split():
print("Key: ", key, " Plain text: ", plain_text)
该函数接收一个密文作为输入,从1到25枚举凯撒密码的密钥,并对密文进行解密。对于每个解密后的明文,函数检查其中是否包含了常见单词和短语,如果有,就输出解密出的明文和对应的密钥。
下一篇:暴力破解满足我的要求的XOR密钥