python实现凯撒密码加密解密

目录

一、信息加密应用发展阶段

二、凯撒密码程序

三、运行结果:


一、信息加密应用发展阶段

在密码学中,恺撒密码 (英语: Caesar cipher ) ,或称恺撒加密、恺撒变换、变换加密,是一种最简单且最一为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系凯撒密码中,将字母表中的字母平移这个操作就是密码的算法

二、凯撒密码程序

复制代码
def encrypt(text, key):
    cipher_text = ""
    for char in text:
        if char.isalpha():
            if char.isupper():
                cipher_text += chr((ord(char) - 65 + key) % 26 + 65)  # 大写字母加密
            else:
                cipher_text += chr((ord(char) - 97 + key) % 26 + 97)  # 小写字母加密
        elif char.isdigit():
            cipher_text += chr((ord(char) - 48 + key) % 10 + 48)  # 数字加密
        else:
            cipher_text += char  # 特殊字符保持不变
    return cipher_text


def decrypt(cipher_text, key):
    plain_text = ""
    for char in cipher_text:
        if char.isalpha():
            if char.isupper():
                plain_text += chr((ord(char) - 65 - key) % 26 + 65)  # 大写字母解密
            else:
                plain_text += chr((ord(char) - 97 - key) % 26 + 97)  # 小写字母解密
        elif char.isdigit():
            plain_text += chr((ord(char) - 48 - key) % 10 + 48)  # 数字解密
        else:
            plain_text += char  # 特殊字符保持不变
    return plain_text


text = input("请输入明文或密文:")
key = int(input("请输入密钥:"))

cipher_text = encrypt(text, key)
plain_text = decrypt(cipher_text, key)

print("明文:", text)
print("密文:", cipher_text)
print("解密后:", plain_text)

三、运行结果:

相关推荐
该用户已不存在4 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP6 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805112 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下12 小时前
最终的信号类
开发语言·c++·算法
c8i12 小时前
python中类的基本结构、特殊属性于MRO理解
python
echoarts12 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin050612 小时前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix12 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
Doris_202313 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202313 小时前
Python 模式匹配match case
前端·后端·python