Python基础编程入门实例:恺撒密码

Python基础编程入门实例:恺撒密码

一、什么是恺撒密码

  • 恺撒撒密码是古罗马恺撒大帝用来对军事情报进行加密的算法,它采用了替换方法对信息中的每一个英文字符循环替换为字母表序列该字符后面第三个字符:

原文:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

在这里插入图片描述

  • 原文字符P,其密文字符C满足如下条件:

C = ( P + 3 ) mod 26

  • 解密方法反之,满足:

P = ( C – 3 ) mod 26

二、程序运行环境

程序运行环境是:pycharm2021
在这里插入图片描述

三、恺撒密码:加密

  • 恺撒密码的加密算法程序首先接收用户输入的文本
  • 然后对字母a-z和字母A-Z按照密码算法进行转换

3.1、恺撒密码加密实例程序

在这里插入图片描述

# 恺撒密码加密
def Caesar_PW_Encryption():
    inputText = input("请输入明文文本: ")
    for index in inputText:
        if "a" <= index <= "z":
            print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='')
        elif "A" <= index <= "Z":
            print(chr(ord("A") 
  • 41
    点赞
  • 145
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 35
    评论
密码是一种简单的加密算法,通过将字母按照一定的偏移量进行替换来实现加密和解密。在Python中实现凯密码可以通过定义一个字母表,并利用其索引进行偏移计算。根据引用中的代码示例,我们可以给出以下Python代码来实现凯密码的加密和解密功能: ```python import string upper_list = string.ascii_uppercase lower_list = string.ascii_lowercase def encryption(source): offset = 5 result = '' for c in source: if c in lower_list: index = (lower_list.index(c) + offset) % len(lower_list) result += lower_list[index] elif c in upper_list: index = (upper_list.index(c) + offset) % len(lower_list) result += upper_list[index] return result def decryption(result): offset = 5 source = '' for c in result: if c in lower_list: index = (lower_list.index(c) - offset) % len(lower_list) source += lower_list[index] elif c in upper_list: index = (upper_list.index(c) - offset) % len(lower_list) source += upper_list[index] return source if __name__ == '__main__': source = "JiaYou" encrypted_result = encryption(source) decrypted_result = decryption(encrypted_result) print(encrypted_result) print(decrypted_result) ``` 以上代码中,`encryption`函数用于将源字符串进行加密,`decryption`函数用于将加密结果进行解密。在`if __name__ == '__main__'`部分,我们可以看到使用示例,输入"JiaYou"字符串进行加密后得到"OnfDtz",再对加密结果进行解密得到原始字符串"JiaYou"。
评论 35
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程爱好者-阿新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值