Search code examples
pythonaespycrypto

Pycrypto: Incrementing AES Counter Mode


I'm really confused about how to do AES decryption in pycrypto using counter mode. As I understand the process, if I start with a known IV to decrypt the first block, then for each successive block, I have to increment the IV. But I don't get how to do this.

Also, I am totally new to python, as you will readily see. My problem lies somewhere in how I am implementing my class and how I am calling it from the decryptor.

Here is the code that I have written thus far:

class IVCounter(object):
    def incrIV(self):
        return self[:15] + chr(ord(self[15:]) + 1)

def decryptCTR(key, ciphertext):

    #convert the key into a 16 byte string
    key = array.array('B', key.decode("hex")).tostring()

    #convert the iv into a 16 byte string
    iv = array.array('B', iv.decode("hex")).tostring()

    print AES.new(key, mode, counter=IVCounter.incrIV(iv)).decrypt(ciphertext)
    return

Here is the error that I get:

TypeError: unbound method incrIV() must be called with IVCounter instance as first argument (got str instance instead)

No matter what I try, I can't get this to work. Can somebody help straighten me out?

Thanks!


Solution

  • class IVCounter(object):
        @staticmethod
        def incrIV(arry):
            return arry[:15] + chr(ord(arry[15:]) + 1)
    

    It's complaining because it expects the first argument to be an instance. Turn that off with the staticmethod decorator.