I am trying to use python 3.7.3 to encrypt a given plaintext with a given key and a given iv. I am unfamiliar with python encryption libraries but have looked around for a couple hours trying to figure this out, and I am unable to.

I have tired using the pycryptodome library as I have been unable to use crypto and pycrypto (keep getting errors when I install them, maybe because I am on windows?).

from Crypto.Cipher import AES
from Crypto.Util import Counter

data = b"plaintext"
key = b"5A557AC90890B2ACD59C536FE4279BBC"
iv = b"5A557AC90890B2ACD59C536FE4279BBC"

counter = Counter.new(128, initial_value=iv)
cipher = AES.new(key, AES.MODE_CTR, counter=counter)

enc = cipher.encrypt(data)


My end result is to print out the encrypted string, but currently I am getting various errors such as "not supported between instances of 'bytes' and 'int'"

1 Answers

l'L'l On

Your code does not use Counter correctly. You are trying to use hexidecimal where an integer should be, and even if you converted your iv value to an integer it would be too large.

initial_value (integer) - The initial value of the counter. Default value is 1.

So changing the code to the following would work for example:

counter = Counter.new(128, initial_value=1)

If you want to randomize the iv you could do something such as:

iv = int.from_bytes(os.urandom(16), sys.byteorder)
counter = Counter.new(128, initial_value=iv)