当前位置: 首页 > news >正文

使用 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

相关文章:

  • 64. 评论日记
  • C++ Primer Plus 章节编程题练习 1-9章包含题目,答案以及知识点总结
  • 企业级RAG行业应用落地方案——阿里云百炼
  • 阿里云域名解析
  • 循环链表的基本操作及C语言代码实现
  • 高性能编程之分支预测
  • Mysql数据库基本操作-DML
  • 阿里计算机专业面试黄金宝典2
  • Hadoop大数据平台部署(Hadoop3.2.4+Hive4.0.1)
  • RabbitMQ 深度解析:从基础到高级应用的全面指南
  • 使用 Axios 进行 API 请求与接口封装
  • 傲梅分区助手单文件版:无损分区管理工具
  • 正版金币捕鱼海洋管家APP源码结构解析与运行环境说明
  • 智慧酒店企业站官网-前端静态网站模板【前端练习项目】
  • 多线性读取数据实现QCustomPlot瀑布图
  • javaSE.抛出异常
  • 2025天梯赛 L2专项训练
  • 项目中引入 Redis 及 常用五种数据类型
  • Django:高效构建现代Web应用的利器
  • MAC Mini M4 上测试Detectron2 图像识别库
  • “90后”樊鑫履新乌兰察布市察右中旗副旗长人选
  • 挤占学生伙食费、公务考察到景区旅游……青岛通报5起违规典型问题
  • 上海首个航空前置货站落户松江综合保税区,通关效率可提升30%
  • 魔都眼·上海车展⑥|周六客流超13.5万人次,创开展新高
  • 美施压拉美国家选边站队,外交部:搞阵营对抗注定失败
  • 3岁男童疑遭父亲虐待,杭州警方:在异地发生,嫌疑人已被抓