乘法密码(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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM