密码学:凯撒密码(移位密码)原理、加密与解密(Python代码示例)

原理

凯撒密码(移位密码):是一种替换加密,明文中的所有字母都在字母表上向后或向前按照一个固定数目进行偏移后被替换成密文。

例如,偏移量为3位的时候:A对应D,B对应E,C对应F等

当偏移量为13位的时候,凯撒密码又叫回转密码ROT13):明文加密得到密文,密文再加密就会得到明文(因为偏移量为13位,一共26个字母,加密两次就会回到明文了),在CTF中题目关键字眼会有回转、回旋、十三踢等字眼。

题目:阿哒,看我回旋十三踢!
密文:Nusynt
明文:AHflag

加密

def caesar_cipher(plaintext, shift): ciphertext = "" for char in plaintext: if char.isalpha(): # 将字母转换为0-25之间的数字,a为0,b为1,依此类推 char_num = ord(char.lower()) - ord('a') # 将数字加上偏移量,并对26取模 shifted_num = (char_num + shift) % 26 # 将数字转换回字母 shifted_char = chr(shifted_num + ord('a')) # 如果原来的字母是大写,就将加密后的字母也变成大写 if char.isupper(): shifted_char = shifted_char.upper() ciphertext += shifted_char else: # 如果不是字母,就不进行加密 ciphertext += char return ciphertext # 获取用户输入的明文和偏移量 plaintext = input("请输入明文:") shift = int(input("请输入偏移量:")) # 调用函数进行加密 ciphertext = caesar_cipher(plaintext, shift) # 输出加密后的密文 print("加密后的密文为:", ciphertext)

解密(枚举法)

def caesar_cipher_decrypt(ciphertext, max_shift): """ 用凯撒密码解密密文,展示所有可能的解密结果 参数: ciphertext -- 密文字符串 max_shift -- 最大位移量 返回值: 无返回值,直接打印所有解密结果 """ for shift in range(max_shift + 1): plaintext = "" for char in ciphertext: if char.isalpha(): # 将字母转换为0-25之间的数字,a为0,b为1,依此类推 char_num = ord(char.lower()) - ord('a') # 将数字加上偏移量,并对26取模 shifted_num = (char_num - shift) % 26 # 将数字转换回字母 shifted_char = chr(shifted_num + ord('a')) # 如果原来的字母是大写,就将加密后的字母也变成大写 if char.isupper(): shifted_char = shifted_char.upper() plaintext += shifted_char else: # 如果不是字母,就不进行解密 plaintext += char # 打印解密结果 print(f"Shift = {shift}: {plaintext}") ciphertext = input("请输入密文:") max_shift = 25 caesar_cipher_decrypt(ciphertext, max_shift)

__EOF__

本文作者stonechen
本文链接https://www.cnblogs.com/stonechen/p/caesar_cipher.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   没事摸摸小肚子  阅读(4977)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示