Search code examples
pythonencryptionaes

Getting error while calling class method using Python


I need to encrypt and decrypt the input text using Python but here I am getting following error.

Traceback (most recent call last):
  File "crypto.py", line 21, in <module>
    encrypt = AESCipher()
TypeError: __init__() takes exactly 2 arguments (1 given)

I am providing my code below.

import base64
from Crypto.Cipher import AES
from Crypto import Random

class AESCipher:
    def __init__( self, thecarkey ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) ) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

encrypt = AESCipher()
passw = encrypt.encrypt('subhra123@')
print(passw)

Here I need to encrypt the text using the Crypto.Cipher defined inside the class but getting the above error.


Solution

  • Your AESCipher requires argument thecarkey for object initiation.

    so it should be AESCipher('somekey'). However there's another bug with your class. The argument thecarkey is never used, so I assume it should be just key:

    class AESCipher:
        def __init__( self, key):
            self.key = key
    ...
    encrypt = AESCipher('somekey')