Vigenere加密与解密

工具 :anaconda3

加密

def encrypt(message,key):#加密
    cipher = ''
    non_alpha_count = 0
    for i in range (len(message)):#遍历
        if message[i].isalpha():#判断是否为字母
            if message[i].islower():##判断是否为小写
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (message[i]) - ord('a') + offset) % 26 + ord('a'))
            else:#大写字母
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (message[i]) - ord('A') + offset) % 26 + ord('A'))        
        else:#非字母,就记下
            cipher += message[i]
            non_alpha_count += 1
    return cipher

message = 'Figure out number of sectors to read'
key = 'quick'
print (encrypt(message,key))

结果
在这里插入图片描述

解密

解密其实就是加密的反动作

def d

你可能感兴趣的:(密码学)