我正在尝试使用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'
如果您对我的程序/解决方案的架构有任何建议,请随时向我启发。
答案 0 :(得分:1)
我应用了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)