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