Search code examples
pythonaes

Solution for: TypeError: object of type 'NoneType' has no len()


So, I was messing a bit with pyaes library and I just wanted to encrypt and decrypt a simple string so I created this 2 functions:

def aes_encrypt(key, plaintext):
   aes = pyaes.AESModeOfOperationCTR(key)
   encrypted_text = aes.encrypt(plaintext)
   print(encrypted_text)

def aes_decrypt(key, encrypted_text):
   aes = pyaes.AESModeOfOperationCTR(key)
   decrypted_text = aes.decrypt(encrypted_text)
   print(decrypted_text)

The key is generated using key_265 = os.urandom(32) And I tried to execute the following lines:

encrypted_text = aes_encrypt(key_256, "Hi World!")
decrypted_text = aes_decrypt(key_256, encrypted_text)

But I am getting this error:while len(self._remaining_counter) < len(plaintext): TypeError: object of type 'NoneType' has no len()

Someone can explain me why is this happening and tell me a possible solution?

This might be a dupe post but I havent found the solution on other similar threads.


Solution

  • I sat here, looking at pyaes implementation, thinking "but it should work"...

    The problem is your function.

    encrypted_text = aes_encrypt(key_256, "Hi World!")
    

    What is the value of encrypted_text? Let's see the function:

    def aes_encrypt(key, plaintext):
       aes = pyaes.AESModeOfOperationCTR(key)
       encrypted_text = aes.encrypt(plaintext)
       print(encrypted_text)
    

    There's no return. Printing is not the same as returning. The function therefore implicitly returns None.


    Fix: add return encrypted_text after print. + The same for decryption.