想知道通过openssl将AES_128_CTR加密转换为PyCrypto的正确方法。
首先,我通过openssl进行了如下加密:
openssl enc -aes-128-ctr -in input.mp4 -out output.openssl.mp4 -K 7842f0a1ebc38f44e3e0c81943f68582 -iv d01f40dfc8ec8cd9
然后,我尝试通过PyCrypto进行相同的操作:
from Crypto.Cipher import AES
from Crypto.Util import Counter
key = '7842f0a1ebc38f44e3e0c81943f68582'
iv = 'd01f40dfc8ec8cd9'
ctr_e = Counter.new(128, initial_value=int(iv, 16))
encryptor = AES.new(key.decode('hex'), AES.MODE_CTR, counter=ctr_e)
with open('output.pycrypto.mp4', 'wb') as fout:
with open('input.mp4', 'rb') as fin:
fout.write(encryptor.encrypt(fin.read()))
我认为它们应该相似,但事实并非如此:
diff output.openssl.mp4 output.pycrypto.mp4
Binary files output.openssl.mp4 and output.pycrypto.mp4 differ
OpenSSL的行为符合预期(幸运的是,命令行缺少此事实的文档),并将给定的IV用作大字节序计数器的最左字节。换句话说,给定的字节是16字节计数器的最高有效部分。问题中的代码使用IV作为初始计数器值,即,它被解释为计数器的最低有效部分。
现在,我花了一些时间来修复Python代码,因为Counter
我必须解决的类存在两个问题:
因此,事不宜迟:
from Crypto.Cipher import AES
from Crypto.Util import Counter
key = '7842f0a1ebc38f44e3e0c81943f68582'.decode('hex')
iv = 'd01f40dfc8ec8cd9'.decode('hex')
ctr_e = Counter.new(64, prefix=iv, initial_value=0)
encryptor = AES.new(key, AES.MODE_CTR, counter=ctr_e)
with open('output.pycrypto.mp4', 'wb') as fout:
with open('input.mp4', 'rb') as fin:
fout.write(encryptor.encrypt(fin.read()))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句