首页 > 解决方案 > 密码学 - 如何使用 ofb 模式实现 MARS?

问题描述

我正在尝试在 python 中为我正在处理的项目找到一个使用OFB操作模式的MARS算法的实现,但我找不到一个可行的。

我在stackoverflow中只找到了OFB模式的实现

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

plainText = b"Lorem ipsum dolor sit amet, consectetur adipiscing e"
key = b"ANAAREMEREAAAAAA"


def ofbEnc(plainText, key):
    pos = 0
    cipherTextChunks = []
    iv = get_random_bytes(16)
    originalIV = iv
    cipher = AES.new(key, AES.MODE_ECB)

    if len(plainText) % 16 != 0:
        plainText += b"1"
    while len(plainText) % 16 != 0:
        plainText += b"0"
    while pos + 16 <= len(plainText):
        toXor = cipher.encrypt(iv)
        nextPos = pos + 16
        toEnc = plainText[pos:nextPos]
        cipherText = bytes([toXor[i] ^ toEnc[i] for i in range(16)])
        cipherTextChunks.append(cipherText)
        pos += 16
        iv = toXor
    return (originalIV, cipherTextChunks)


def ofbDec(cipherTextChunks, key, iv):
    plainText = b""
    cipher = AES.new(key, AES.MODE_ECB)
    for chunk in cipherTextChunks:
        toXor = cipher.encrypt(iv)
        plainText += bytes([toXor[i] ^ chunk[i] for i in range(15)])
        iv = toXor
    while plainText[-1] == 48:
        plainText = plainText[0:-1]
    if plainText[-1] == 49:
        plainText = plainText[0:-1]
    return plainText


iv, result = ofbEnc(plainText, key)
print(iv, result)

plain = ofbDec(result, key, iv)
print(plain)

但我在 python 中找不到MARS实现。

另外,为了理解一些事情,当我在OFB模式下使用MARS加密时,这意味着我使用MARS算法加密每个块,然后对于每个块,我使用OFB模式算法再次加密它?

例如:我正在尝试使用 128 位加密字符串:'text',而MARS将使用 64 位块大小进行加密。

所以我将字符串分成 2 个块:b1、b2,每个块 64 位。

对于我用MARS算法加密的每个块 b1、b2 ,我们称它们为 encb1、encb2。

那么对于每个加密块 encb1, encb2 我用OFB算法加密它们?

标签: pythonencryptioncryptographyblock-cipher

解决方案


推荐阅读