欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python实现凯撒密码加解密

程序员文章站 2022-07-09 13:45:57
...

源代码

def CaesarEncode(PlainText,shif):    #加密
    TextList = []
    AsciiList = []
    ResultList = []
    shift = int(shif)
    for i in PlainText:
        TextList.append(i)
    for j in TextList:
        num = ord(j)
        AsciiList.append(num)
    for k in AsciiList:
        tmp = int(k)
        addnum = tmp + shift
        Str = chr(addnum)
        ResultList.append(Str)
    ResultStr = "".join(ResultList)
    return ResultStr

def CaesarDecode(CipherText,shif):     #解密
    NumList = []
    StrList = []
    shift = int(shif)
    for i in CipherText:
        Num = ord(i)
        NumList.append(Num)
    for d in NumList:
        j = int(d)
        if(j - shift < 97):
            num = j - shift + 26
            StrList.append(chr(num))
        else:
            if(j - shift > 123):
                num = j - shift - 26
                StrList.append(chr(num))
            else:
                num = j - shift
                StrList.append(chr(num))
            
    PlainText = "".join(StrList)
    return PlainText

其实还可以继续优化一下
就是在解密时将26种情况同时列出来
大家可以下去自己试试哦