我正在尝试使用pycryptodome库实现AES加密的OFB模式,并且我在理解应该为密码提供什么输入时遇到了问题。我知道pycryptodome已经实现了OFB,但我需要将纯文本拆分为字节,应用OFB的适当步骤来加密它与ECB模式的AES密码,然后解密它。
在python中,像b'\x16\xa8W\xed.)\xc4\xb8x\xd6\xcf\x7f\xf3\xe3;^'
这样的字节字符串是如何工作的?
我需要获取这样一个字节字符串,对其进行加密,然后将其一分为二,并将其与纯文本的8个字节进行XOR运算。对我来说,理解并做到这一点最简单的方法是用AES对IV (上面的字节字符串)进行加密,然后将它和纯文本转换为二进制和xor,然后将它们转换回字节字符串。我该怎么做呢?
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'
如果您对我的程序/解决我的问题的方法有更好的架构有任何建议,请随时启发我。
发布于 2019-01-09 13:22:58
我应用了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)
https://stackoverflow.com/questions/54107888
复制