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)

三、运行结果:

相关推荐
木子杳衫34 分钟前
【软件开发】管理类系统
python·web开发
程序员小远4 小时前
银行测试:第三方支付平台业务流,功能/性能/安全测试方法
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
Predestination王瀞潞4 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力5 小时前
C++继承
开发语言·c++
猫头虎6 小时前
如何查看局域网内IP冲突问题?如何查看局域网IP环绕问题?arp -a命令如何使用?
网络·python·网络协议·tcp/ip·开源·pandas·pip
沿着路走到底6 小时前
python 基础
开发语言·python
沐知全栈开发7 小时前
C# 委托(Delegate)
开发语言
任子菲阳7 小时前
学Java第三十四天-----抽象类和抽象方法
java·开发语言
烛阴8 小时前
武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法
前端·python
lisw058 小时前
SolidWorks:现代工程设计与数字制造的核心平台
人工智能·机器学习·青少年编程·软件工程·制造