古典密码学 凯撒密码 Python 实现 Caesar Cipher in Python
原理
将26个英文字母分别对应一个数字,循环移位。移位的个数是密钥。
- 如密钥是 B,则移位 1 位;
- 如密钥是 C,则移位 2 位,以此类推。
密钥是C(移位2位)对应图如图所示:
代码
class CaesarCipher:
map1 = { "A":0 ,"B":1 ,"C":2 ,"D":3 ,"E":4 ,"F":5 ,"G":6 ,"H":7 ,"I":8 ,"J":9 ,"K":10 ,"L":11 ,"M":12 ,"N":13 ,"O":14 ,"P":15 ,"Q":16 ,"R":17 ,"S":18 ,"T":19 ,"U":20 ,"V":21 ,"W":22 ,"X":23 ,"Y":24 ,"Z":25
,0:"A" ,1:"B" ,2:"C" ,3:"D" ,4:"E" ,5:"F" ,6:"G" ,7:"H" ,8:"I" ,9:"J" ,10:"K" ,11:"L" ,12:"M" ,13:"N" ,14:"O" ,15:"P" ,16:"Q" ,17:"R" ,18:"S" ,19:"T" ,20:"U" ,21:"V" ,22:"W" ,23:"X" ,24:"Y" ,25:"Z" }
def __init__(self):
pass
def enc(self, plaintext:str, key:str)->str:
"""加密函数
Attribute:
- plaintext: 明文
- key: 密钥
"""
plaintext = plaintext.upper()
assert sum([i not in map1 for i in set(list(plaintext))]) = = 0,"Exist charactor not in plaintext or cyphertext space."
return "".join([map1[(map1[i]+map1[t_key])%26] for i in plaintext])
def dec(self,cyphertext:str, key:str)->str:
"""解密函数
Attribute:
- cyphertext: 密文
- key: 明文"""
cyphertext = cyphertext.upper()
assert sum([i not in map1 for i in set(list(cyphertext))]) = = 0,"Exist charactor not in plaintext or cyphertext space."
return "".join([map1[(map1[i]-map1[t_key])%26] for i in cyphertext])
实验
输入在明文域内的明文:
t_plain = "HappyBirthday"
t_key = "C"
t = CaesarCipher()
print("明文是:",t_plain)
t_cypher = t.enc(t_plain, t_key)
print("密文是:",t_cypher)
t_result = t.dec(t_cypher, t_key)
print("解密结果是:",t_result)
结果是:
明文是: HappyBirthday
密文是: JCRRADKTVJFCA
解密结果是: HAPPYBIRTHDAY
输入不在明文域内的明文:
t_plain = "HappyBirthday!!"
t_key = "B"
print("明文是:",t_plain)
t_cypher = t.enc(t_plain, t_key)
结果是:
AssertionError: Exist charactor not in plaintext or cyphertext space.