凯撒密码是古罗马凯撒皇帝用来对军事情报进行加密的算法,它采用了替换方法将信息中的每一个英文字母循环替换为字母表序列中该字符的后面三个,对应关系如下:
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 = chr(ord("A") + (ord(P) - ord(A) + 3)%26)
解密方法如下:
P = chr(ord("A") + (ord(P) - ord(A) - 3)%26)
对应的Python程序如下:
"""
Date:2019-03-26
Author:MaoChuangAn
Descript:凯撒加密算法
"""
#加密函数
def CeaserEncode():
#ptext = input("请输入文本文件")
etext=""
ptext = "This is an excellent Python book."
for p in ptext:
if "a"<=p<="z":
etext = etext + chr(ord("a")+(ord(p)-ord("a")+3)%26)
elif "A"<=p<="Z":
etext = etext + chr(ord("A") + (ord(p)-ord("A")+3)%26)
else:
etext = etext + p
print("要加密的文字:{}".format(ptext))
print("加密后的文字:{}".format(etext))
return ptext,etext
#解密函数
def Decode(text):
ptext=""
for p in text:
if "a"<=p<="z":
ptext = ptext + chr(ord("a")+(ord(p)-ord("a")-3)%26)
elif "A"<=p<="Z":
ptext = ptext + chr(ord("A")+(ord(p)-ord("A")-3)%26)
else:
ptext = ptext + p
print("解密后的文字:{}".format(ptext))
return ptext
S,S1=CeaserEncode()
S2=Decode(S1)
if(S==S2):
print("加密解密成功")
else:
print("加密解密失败")