凯撒密码加密的算法实现(python)

凯撒密码加密的算法实现

#凯撒密码


#要加解密的字符串
message='This is my secret message.'

#加解密密钥
key=13

#程序是加密还是解密
mode='encrypt' #设置为encrypt或decrypt

#可能被加解密的符号
SYMBOLS='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'

#存储消息的加解密形式
translated=''

for symbol in message:
    #注意:只能加解密SYMBOLS字符串中的符号
    if symbol in SYMBOLS:
        symbolIndex=SYMBOLS.find(symbol)

        #执行加解密
        if mode =='encrypt':
            translatedIndex=symbolIndex+key
        if mode =='decrypt':
            translatedIndex=symbolIndex-key

        #如果需要,执行回环
        if translatedIndex>=len(SYMBOLS):
            translatedIndex=translatedIndex-len(SYMBOLS)
        elif translatedIndex <= 0:
            translatedIndex=translatedIndex+len(SYMBOLS)

        translated=translated+SYMBOLS[translatedIndex]

    else:
        #添加未加解密的字符
        translated=translated+symbol

    #输出translated字符串
print(translated)

posted @ 2021-08-11 12:03  SwordCreater  阅读(2910)  评论(1编辑  收藏  举报