简体   繁体   中英

Pycrypto AES-CTR implementation

I am new to python and pycrypto. I am trying to implement AES-CTR. To check my program for correct ciphering I tried to use test sequences from NIST SP 800-38A standard (section F.5). But I do not get correct result. What am I doing wrong?

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"))

Result:

0008007df81ad564b9aadd6b883fef16

But the expected result ( ciphertext ) is:

874d6191b620e3261bef6864990db6ce

In the NIST SP 800-38A standard (section F.5.1), the input to the CTR-AES128 encryption operation is called plaintext not input block .

If you use the plaintext ( 6bc1bee22e409f96e93d7e117393172a ) you get the correct result, the ciphertext 874d6191b620e3261bef6864990db6ce .

I tried this.

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"))

got result

874d6191b620e3261bef6864990db6ce

use binary data work for me, and str.encode("hex") is not recommended

Other than using the appropriate plain text value as mention by SquareRootOfTwentyThree, you should also consider the type of data being used in the code. The PyCrypto documentation suggests that the data type of keys to be bytes , whereas the counter can be of type int or bytes .

You will need to use appropriate datatype to get the cipher text mentioned in NIST SP 800-38A. Kameel's code works, I have included the code in my answer as well.

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"))



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM