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)

三、运行结果:

相关推荐
星辰大海的精灵7 分钟前
基于Dify+MCP实现通过微信发送天气信息给好友
人工智能·后端·python
精灵vector12 分钟前
Agent短期记忆的几种持久化存储方式
人工智能·python
flyair_China24 分钟前
【云架构】
开发语言·php
北京_宏哥27 分钟前
🔥Python零基础从入门到精通详细教程4-数据类型的转换- 上篇
前端·python·面试
Chef_Chen30 分钟前
从0开始学习R语言--Day20-ARIMA与格兰杰因果检验
开发语言·学习·r语言
zh_xuan31 分钟前
c++ std::pair
开发语言·c++
乾巫宇宙国监察特使37 分钟前
Python的设计模式
python·测试
Hockor1 小时前
写给前端的 Python 教程四(列表/元组)
前端·后端·python
CodeWithMe1 小时前
【C/C++】EBO空基类优化介绍
开发语言·c++
这里有鱼汤1 小时前
熟练掌握MACD这8种形态,让你少走三年弯路(附Python量化代码)| 建议收藏
后端·python