1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class CaesarCipher: def __init__(self): self.letter_map = {'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 encryption(self, plaintext, key): ''' 加密函数 ''' plaintext = plaintext.upper() cyphertext = [] for i in plaintext: if i.isalpha(): cyphertext.append(self.letter_map[(self.letter_map[i] + key)%26]) else: cyphertext.append(i) return ''.join(cyphertext)
def decryption(self, cyphertext, key): ''' 解密函数 ''' cyphertext = cyphertext.upper() plaintext = [] for i in cyphertext: if i.isalpha(): plaintext.append(self.letter_map[(self.letter_map[i] - key)%26]) else: plaintext.append(i) return ''.join(plaintext)
t_plain = '12.25 HappyBirthday!' t_key = 3 t = CaesarCipher() print('明文是:', t_plain) t_cypher = t.encryption(t_plain, t_key) print('密文是:', t_cypher) t_result = t.decryption(t_cypher, t_key) print('解密结果是:', t_result)
|