Python非对称加密案例

有张三和李四两人需要沟通

        张三要求的加密算法是:采用凯撒加密算法,字母右移5位,

        李四要求的加密算法是:大小写互换。

        要求双方在不知道对方加密算法的前提下,双方实现文本的传输,并且确保传输过程始终是加密的。

import string
upper_list = string.ascii_uppercase
lower_list = string.ascii_lowercase
# 对大小写利用凯撒算法右移5位
def encrypt_zhang(source):
    dest = ''
    for c in source:
        # 如果是大写的情况
        if c in upper_list:
            index = (upper_list.index(c) + 5) % 26
            dest += upper_list[index]
        elif c in lower_list:
            index = (lower_list.index(c) + 5) % 26
            dest += lower_list[index]
    return dest

# 对凯撒加密后的字符串进行左移5位实现解密
def decrypt_zhang(source):
    dest = ''
    for c in source:
        if c in upper_list:
            index = (upper_list.index(c) - 5) % 26
            dest += upper_list[index]
        elif c in lower_list:
            index = (lower_list.index(c) - 5) % 26
            dest += lower_list[index]
    return dest

#  李四的算法是大小写互换,所以加解密算法是一样的

def convert_li(source):
    dest = ''
    for c in source:
        if ord(c) >= 65 and ord(c) <= 90:
            dest += chr(ord(c) + 32)
        elif ord(c) >= 97 and ord(c) <= 122:
            dest += chr(ord(c) - 32)
    return dest

if __name__ == '__main__':
    source = 'Goodluck'
    print(source)
    res_1 = encrypt_zhang(source)
    print(res_1)
    res_2 = convert_li(res_1)
    print(res_2)
    res_3 = decrypt_zhang(res_2)
    print(res_3)
    res_4 = convert_li(res_3)
    print(res_4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值