python 中的 AES OFB 实现与 pycryptodome

AES OFB implementation in python with pycryptodome

我正在尝试使用 pycryptodome 库实现 AES 加密的 OFB 模式,但我在理解我应该为密码提供什么输入时遇到了问题。我知道 pycryptodome 已经实现了 OFB,但我需要将纯文本分解成字节,应用 OFB 的适当步骤用带有 ECB 模式的 AES 密码加密它,然后解密它。

b'\x16\xa8W\xed.)\xc4\xb8x\xd6\xcf\x7f\xf3\xe3;^' 等字节串如何在 python 中工作?

我需要对这样一个字节串进行加密,然后将其分成两半并与纯文本的 8 个字节进行异或运算。对我来说理解和执行此操作的最简单方法是使用 AES 加密 IV(上面的字节字符串),然后将其和纯文本转换为二进制并对它们进行异或运算,然后将它们转换回字节串。我该怎么做?

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"
iv = get_random_bytes(32)

print("iv: ", iv)

cipher = AES.new(key, AES.MODE_ECB)
toXor = cipher.encrypt(iv)

print("toXor: ", toXor)

"""
toXorF=first half of toXor
ivS=second half of iv

cipherText=toXorF xored to first 8 bytes of plainText
iv=ivS + toXorS
"""

打印输出:

iv:  b"v'xg;\xd7h\xfc\xf2\xa4[\r\xee]J\x1eu\xa5\xe68\xa3a\xde\x02(\xc1\xe0\xc9z\x0f\xc3n"
toXor:  b'\x97\xbex\xfc\xb6\xbb\x85\xccZ\xc4\xe4\x9d\xd6M\xf2\xd7\xb7\xbf\xd0\xbe\xa5A\xd6\xee\x07U\xe0S\x7f\x88\xea\xcd'

如果您对我的program/approach问题的更好架构有任何建议,请随时启发我。

我应用了 t.m.adam 建议的内容,这是完美运行的最终代码。

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)