Pycrypto AES-CTR 实现
我刚开始学习Python和pycrypto。
我想实现AES-CTR加密。为了检查我的程序是否正确加密,我尝试使用NIST SP 800-38A标准中的测试序列(第F.5节)。但是我得不到正确的结果。我哪里做错了呢?
from Crypto.Cipher import AES
from Crypto.Utils import Counter
CTRkey="2b7e151628aed2a6abf7158809cf4f3c"
ctr=Counter.new(128, initial_value=int("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",16))
cipherCTR=AES.new(CTRkey, AES.MODE_CTR, counter=ctr)
print(cipherCTR.encrypt("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff".decode("hex")).encode("hex"))
结果:
0008007df81ad564b9aadd6b883fef16
但是预期的结果(密文)是:
874d6191b620e3261bef6864990db6ce
3 个回答
0
除了使用SquareRootOfTwentyThree提到的合适的纯文本值外,你还应该考虑代码中使用的数据类型。PyCrypto的文档建议,密钥的数据类型应该是字节(bytes),而计数器可以是整数(int)或字节(bytes)。
你需要使用合适的数据类型,才能得到NIST SP 800-38A中提到的密文。Kameel的代码是可以工作的,我在我的回答中也包含了这段代码。
from Crypto.Cipher import AES
import Crypto.Utils.Counter
import binascii
CTRkey = b'\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
iv = b'\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
plain_text = b'\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a'
ctr = Crypto.UtilsCounter.new(128, initial_value=int(binascii.hexlify(iv), 16))
cipherCTR = AES.new(CTRkey, AES.MODE_CTR, counter=ctr)
print(cipherCTR.encrypt(plain_text).encode("hex"))
1
我试过这个。
import Crypto.Cipher.AES
import Crypto.Util.Counter
import binascii
key = b'\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
iv = b'\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
text = b'\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a'
ctr = Crypto.Util.Counter.new(128, initial_value=int(binascii.hexlify(iv), 16))
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR, counter=ctr)
print(cipher.encrypt(text).encode("hex"))
得到了结果
874d6191b620e3261bef6864990db6ce
使用二进制数据对我来说有效,而 str.encode("hex") 不推荐使用。
3
在NIST SP 800-38A标准的F.5.1节中,CTR-AES128加密操作的输入被称为明文,而不是输入块。
如果你使用这个明文(6bc1bee22e409f96e93d7e117393172a
),你会得到正确的结果,也就是密文 874d6191b620e3261bef6864990db6ce
。