乘法密码(Multiplicative Cipher)体制的加密和解密

乘积密码体制是通过“乘积”组合密码体制。在现代密码体制的设计中非常重要,比如高级加密标准 AES。

代码实现(Python 3)

#print('***** MultiplicativeCipher *****')
#multiplicative_cipher_encrypt('hello',5) #result is 'JUDDS'.
#multiplicative_cipher_decrypt('JUDDS',5) #result is 'hello'.
#multiplicative_cipher_encrypt('thiscryptosystemisnotsecure',11)


def multiplicative_cipher_encrypt(message: str, key):
    SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    translated = ''

    if gcd(key, 26) != 1:
        print(f'{key} and 26 are not coprime.')
        return
    message = message.upper()
    for symbol in message:
        if symbol in SYMBOLS:
            symbolIndex = SYMBOLS.find(symbol)
            translatedIndex = (key * symbolIndex) % 26
            translated = translated + SYMBOLS[translatedIndex]
        else:
            translated = translated + symbol
    print(translated)


def multiplicative_cipher_decrypt(message: str, key):
    SYMBOLS = 'abcdefghijklmnopqrstuvwxyz'
    translated = ''

    message = message.lower()
    key1 = multiplicative_inverse(key)
    for symbol in message:
        if symbol in SYMBOLS:
            symbolIndex = SYMBOLS.find(symbol)
            translatedIndex = (key1 * symbolIndex) % 26
            translated = translated + SYMBOLS[translatedIndex]
        else:
            translated = translated + symbol
    print(translated)


def multiplicative_inverse(key, m=26):
    for n in range(m):
        if key * n % m == 1:
            print(f'The multiplicative_inverse of key {key} is {n}.')
            return n
    return -1


def gcd(a, b):
    while (b):
        a, b = b, a % b
    return a
posted @ 2021-12-21 22:28  vicky2021  阅读(1207)  评论(0编辑  收藏  举报