Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (50.2k points)

I want to create two methods using PyCrypto that accept two arguments: the message and the key, and then encrypt/decrypt the message. How can I do that?

1 Answer

0 votes
by (108k points)

You can refer to the below implementation with 32 bytes and iv to 16 bytes in Python:

import base64

import hashlib

from Crypto import Random

from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key):  = AES.block_size

        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):

        raw = self._pad(raw)

        iv =

        cipher =, AES.MODE_CBC, iv)

        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):

        enc = base64.b64decode(enc)

        iv = enc[:AES.block_size]

        cipher =, AES.MODE_CBC, iv)

        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):

        return s + ( - len(s) % * chr( - len(s) %


    def _unpad(s):

        return s[:-ord(s[len(s)-1:])]

Related questions

Browse Categories