代换密码(Substitution Cipher)体制的加密和解密


另一个比较有名的古典密码体制是代换密码,它是代换密码的一种特殊情形。

在移位密码中,加密和解密都是代数运算,但是在代换密码中,可以认为P和C是26个英文字母,并且可以认为加密和解密的过程直接看作是在一个字母表上的置换。

任意取一置换,即可得到加密函数,见下表(小写字母表示明文,大写字母表示密文): 

按照上表有,等等。而解密函数则是相应的逆置换。

代码实现(Python 3)

'''
代换密码体制加密
e.g. key='XNYAHPOGZQWBTSFLRCVMUEKJDI'
'''
def substitution_cipher_encrypt(text: str, key: str):
    SYMBOLS = 'abcdefghijklmnopqrstuvwxyz'
    translated = ''

    text = text.lower()
    for symbol in text:
        if symbol in SYMBOLS:
            symbolIndex = SYMBOLS.find(symbol)
            translated = translated + key[symbolIndex]
        else:
            translated = translated + symbol
    print(translated)


'''
代换密码体制解密
e.g. key='dlryvohezxwptbgfjqnmuskaci'
'''
def substitution_cipher_decrypt(text: str, key: str):
    SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    translated = ''

    text = text.upper()
    for symbol in text:
        if symbol in SYMBOLS:
            symbolIndex = SYMBOLS.find(symbol)
            translated = translated + key[symbolIndex]
        else:
            translated = translated + symbol
    print(translated)