原文: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
C = ( P + 3 ) mod 26
P = ( C – 3 ) mod 26
程序运行环境是:pycharm2021
# 恺撒密码加密
def Caesar_PW_Encryption():
inputText = input("请输入明文文本: ")
for index in inputText:
if "a" <= index <= "z":
print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='')
elif "A" <= index <= "Z":
print(chr(ord("A") + (ord(index) - ord("A") + 3) % 26), end='')
else:
print(index, end='')
if __name__ == '__main__':
# 恺撒密码加密
Caesar_PW_Encryption()
# 恺撒密码解密
def Ceasar_PW_Decryption():
inputText = input("请输入加密后文本: ")
for index in inputText:
if "a" <= index <= "z":
print(chr(ord("a") + (ord(index) - ord("a") - 3) % 26), end='')
elif "A" <= index <= "Z":
print(chr(ord("A") + (ord(index) - ord("A") - 3) % 26), end='')
else:
print(index, end='')
if __name__ == '__main__':
# 恺撒密码加密
Caesar_PW_Encryption()
# 恺撒密码解密
Ceasar_PW_Decryption()
# 恺撒密码加密
def Caesar_PW_Encryption():
inputText = input("请输入明文文本: ")
for index in inputText:
if "a" <= index <= "z":
print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='')
elif "A" <= index <= "Z":
print(chr(ord("A") + (ord(index) - ord("A") + 3) % 26), end='')
else:
print(index, end='')
# 恺撒密码解密
def Ceasar_PW_Decryption():
inputText = input("请输入加密后文本: ")
for index in inputText:
if "a" <= index <= "z":
print(chr(ord("a") + (ord(index) - ord("a") - 3) % 26), end='')
elif "A" <= index <= "Z":
print(chr(ord("A") + (ord(index) - ord("A") - 3) % 26), end='')
else:
print(index, end='')
if __name__ == '__main__':
# 恺撒密码加密
Caesar_PW_Encryption()
# 恺撒密码解密
Ceasar_PW_Decryption()
本文主要讲解了恺撒密码:采用了替换方法对信息中的每一个英文字符循环替换为字母表序列该字符后面第三个字符。并通过一个实例程序来进一步加强对恺撒密码的理解与运用。