目录

 

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

二、凯撒密码程序

三、运行结果:


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

       在密码学中,恺撒密码 (英语: 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)

三、运行结果:

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐