python实现仿射密码加解密过程

对于仿射密码算法过程这里不做过多讲解,请自行参照教材或者网络资料。这里需要注意的是,默认为加密后的密文要转化为大写字母的形式。下面是用python实现的加解密过程:

密钥为k=(11,4)

(1)加密过程

import string

plaintext_ = string.ascii_lowercase
ciphertext_ = string.ascii_uppercase


#加密算法

def encryption(plaintext):
    cipherarr = [0 for i in range(len(plaintext))]
    plaintext_list = list(plaintext)

    j = 0
    for plaintext_item in plaintext_list:
        for i in range(len(plaintext_)):
            if plaintext_item == plaintext_[i]:
                ciphertext = (11*i+4)%26
                cipherarr[j] = ciphertext_[ciphertext]
                j = j+1

    cipher = ''.join(cipherarr)
    return cipher

while True:
    plaintext = raw_input('请输入明文:')
    cipher = encryption(plaintext)
    if plaintext == 'exit':
        break
    print '密文是:',cipher


(2)解密过程,密钥k的逆元求出后直接带到公式


def decryption(ciphertext):
    plaintext_arr = [0 for i in range(len(ciphertext))]
    cipherlist = list(ciphertext)

    j = 0
    for cipheritem in cipherlist:
        for i in range(len(ciphertext_)):
            if cipheritem == ciphertext_[i]:
                plaintext = (19*i-24)%26
                plaintext_arr[j] = plaintext_[plaintext]
                j = j+1

    plain = ''.join(plaintext_arr)
    return plain

while True:
    ciphertext = raw_input('请输入密文:')
    plain = decryption(ciphertext)
    if ciphertext == 'EXIT':
        break
    print '明文输出为:',plain


你可能感兴趣的:(python实现仿射密码加解密过程)