使用 Python 实现凯撒密码的加密、解密及破译算法
文章目录
- 什么是凯撒密码?
- 凯撒密码的加密算法
- 凯撒密码的解密算法
- 凯撒密码的破译算法
- 凯撒密码的破译算法(升级版)
什么是凯撒密码?
恺撒撒密码是古罗马恺撒大帝用来对军事情报进行加密的算法,它采用了替换方法对信息中的每一个英文字符循环替换为字母表序列该字符后面第三个字符:
原文:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B
介绍链接:凯撒密码介绍
凯撒密码的加密算法
# 假设明文和密文只包含大写字母
Plaintext = "ABC"
Ciphertext = ""
Secret_Key = 3
# 凯撒密码加密算法
for letter in Plaintext:
if ord('A') <= ord(letter) <= ord('Z'):
Ciphertext += chr(ord('A') + (ord(letter) - ord('A') + Secret_Key) % 26)
else:
Ciphertext += letter
凯撒密码的解密算法
# 假设明文和密文只包含大写字母
Plaintext = ""
Ciphertext = "DEF"
Secret_Key = 3
# 凯撒密码解密算法
for letter in Ciphertext:
if ord('A') <= ord(letter) <= ord('Z'):
Plaintext += chr(ord('A') + (ord(letter) - ord('A') - Secret_Key) % 26)
else:
Plaintext += letter
print(Plaintext)
凯撒密码的破译算法
# 假设明文和密文只包含大写字母
Plaintext = ""
Ciphertext = "KHOOR"
# Secret_Key = 3
# 凯撒密码解密算法
# 暴力破解
for Secret_Key in range(1, 27, 1):
Plaintext = ""
for letter in Ciphertext:
if ord('A') <= ord(letter) <= ord('Z'):
Plaintext += chr(ord('A') + (ord(letter) - ord('A') - Secret_Key) % 26)
else:
Plaintext += letter
print("Secret Key:{}\t【Plaintext】{}".format(Secret_Key, Plaintext))
问题:当密文较长,无法准确判断明文内容时该怎么办?
凯撒密码的破译算法(升级版)
import csv
# 读取为字典(需标题行)
def if_word(word):
word = word.lower()
with open('EnWords.csv', mode='r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
if word == row['word']:
return True
return False
# 假设明文和密文只包含大写字母
Plaintext = ""
Ciphertext = "KHOOR"
# Secret_Key = 3
# 凯撒密码解密算法
# 暴力破解
for Secret_Key in range(1, 27, 1):
Plaintext = ""
for letter in Ciphertext:
if ord('A') <= ord(letter) <= ord('Z'):
Plaintext += chr(ord('A') + (ord(letter) - ord('A') - Secret_Key) % 26)
else:
Plaintext += letter
# 1. 使用自然语言处理相关方法检测
# 2. 使用暴力字典查找方式检测
if if_word(Plaintext):
print("Secret Key:{}\t【Plaintext】{}".format(Secret_Key, Plaintext))
break