Python编程练习与解答 练习73:凯撒密码

        最早为人所知的加密例子之-一是尤利乌斯●凯撒(Julius Caesarl使用的。凯撒需要向他的将军们提供书面指示,但他不想让敌人知道他的计划,为了避免信息落入敌人的手中,他发明了后来被称为凯撒密码的密码。
       这个密码背后的思想很简单(同样,它也没有提供针对现代密码破解技术的保护)。原信息中的每个字母移动了3个位置。结果,A变成了D,B变成了E,C变成了F,D变成了G,等等。字母表中的最后三个字母放在开头: X变成A, Y变成B,变成C。非字母字符不被密码修改。
        编写一个实现凯撒密码的程序。允许用户提供消息和移位量然后显示移位后的消息。确保程序同时编码大写和小写字母。程还应该支持负移位值,以便它既可以用于编码消息,也可以用于角码消息

# 设置初始值,移动量
code=(input("请输入要转译的密码"))
count=int(input("请输入移位量"))
#
# 使用for循环,使用ascii码对密码字母进行量化,便于进行转译
# 使用for循环是对每个字母逐个转译,先定义一个空的字符串用于储存转译后的字符串
new_code=""
for i in code:
    #当字母为小写字母
    if "a"<=i<="z":
        # 计算转译后字母位置
        # 新的位置等于原来旧的字母位置加上移位量
        pos=ord(i)+count
        if pos>122:
            pos=pos-122+96
        else:
            pos=pos
        i=chr(pos)
        new_code=new_code+i
    elif "A" <= i <= "Z":
            # 计算转译后字母位置
            # 新的位置等于原来旧的字母位置加上移位量
            pos = ord(i) + count
            if pos > 91:
                pos = pos - 91 + 64
            else:
                pos = pos
            i = chr(pos)
            new_code = new_code + i
print(new_code)


 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
密码是一种简单的加密算法,通过将字母按照一定的偏移量进行替换来实现加密和解密。在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"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值