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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class VigenereCipher: def __init__(self): self.letter_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'} self.letter_map2 = {'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:'g', 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): ''' 加密函数 ''' cyphertext = [] key_list = list(key) cnt = 0 for i in plaintext: if cnt % len(key_list) == 0: cnt = 0 if i.isalpha(): if i.isupper(): cyphertext.append(self.letter_map1[(self.letter_map1[i] + self.letter_map1[key_list[cnt].upper()])%26]) if i.islower(): cyphertext.append(self.letter_map2[(self.letter_map2[i] + self.letter_map2[key_list[cnt].lower()])%26]) cnt += 1 else: cyphertext.append(i) return ''.join(cyphertext)
def decryption(self, cyphertext, key): ''' 解密函数 ''' plaintext = [] key_list = list(key) cnt = 0 for i in cyphertext: if cnt % len(key_list) == 0: cnt = 0 if i.isalpha(): if i.isupper(): plaintext.append(self.letter_map1[(self.letter_map1[i] - self.letter_map1[key_list[cnt].upper()])%26]) if i.islower(): plaintext.append(self.letter_map2[(self.letter_map2[i] - self.letter_map2[key_list[cnt].lower()])%26]) cnt += 1 else: plaintext.append(i) return ''.join(plaintext)
t_plain = '12.25 HappyBirthday!' t_key = 'AMAZE' t = VigenereCipher() 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)
|