凯撒加密

凯撒密码是古罗马凯撒大帝用来对军事情报进行加密的算法,它采用了替换方
法对信息中的每一个英文字符循环替换为字母表序列该字符后面第三个字符,
对应关系如下:
原文: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

实现

我在这里简单增加了对于汉字(Unicode码中基础汉字范围中的汉字)和小写字母的处理,并且我还对于凯撒加密原本固定的偏移量(3)做了调整,可以用户自定义,当然加密和解密必须使用同样的偏移量才能获得到原本的信息。

注:代码中使用了python3.10版本中新增的match语句,如版本低于3.10,请自主修改为普通选择结构。

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
from functools import reduce
def mainView():
    print(f"{'CODING ENGINE BY JASON':#^50s}")
    print(f"{'1.ENCODE 2.DECODE 3.BACK 4.EXIT':#^50s}")
    print(f"{'#':#^50s}")
def main():
    mainView()
    try:
        while True:
            s=list(input(f"{'>':=>2s}Please input text:"))
            while True:
                match input(f"{'>':=>2s}Option:"):
                    case '1':
                        os=int(input(f"{'>':=>2s}Please input the offset of encoding:"))
                        s=list(map(lambda x:encodeOrDecode(x,offset=os),s))
                        print("Result",reduce(lambda x,y:x+y,s),sep=':')
                        #Another way to show
                        #print("Result",reduce(lambda x,y:x+y,map(lambda x:encodeOrDecode(x),s)),sep=':')
                    case '2':
                        os=int(input(f"{'>':=>2s}Please input the offset of encoding:"))
                        s=list(map(lambda x:encodeOrDecode(x,offset=-os),s))
                        print("Result",reduce(lambda x,y:x+y,s),sep=':')
                        #Another show way to show
                        #print("Result",reduce(lambda x,y:x+y,map(lambda x:encodeOrDecode(x,offset=-3),s)),sep=':')
                    case '3':
                        break
                    case '4':
                        quit()
                    case _:
                        print("Please input option again!")
    except Exception as e:
        print("Sorry,there has been an error!")
        print("Error",e,sep=":")
    finally:
        print("Good Bye!")
    
#c - a single char which will be encoded 
#offset - a default int value which is the offset between encoded code and decoded code.
#return encoded c
def encodeOrDecode(c,offset=3):
    unicode=ord(c)
    #Upper case - totality:26
    if unicode>=65 and unicode<=90:
        c=chr(65+((unicode-65+offset)%26))
    #Lower case - totality:26
    elif unicode>=97 and unicode<=122:
        c=chr(97+((unicode-97+offset)%26))
    #Basic Chinese characters - totality:20920
    elif unicode>=int('4E00',16) and unicode<=int('9FA5',16):
        c=chr(int('4E00',16)+((unicode-int('4E00',16)+offset)%20920))
    #Other characters
    else:
        pass
    return c

#def decode(c):
#    return c

#----
main()
#mainView()

输出

##############CODING ENGINE BY JASON##############
#########1.ENCODE 2.DECODE 3.BACK 4.EXIT##########
##################################################
=>Please input text:我是Jason...
=>Option:1
=>Please input the offset of encoding:3
Result:戔昲Mdvrq...
=>Option:2
=>Please input the offset of encoding:3
Result:我是Jason...
=>Option:1
=>Please input the offset of encoding:55
Result:扈晦Mdvrq...
=>Option:2
=>Please input the offset of encoding:55
Result:我是Jason...
=>Option:4
Good Bye!

Q.E.D.


仰望星空,还需脚踏实地。