Python implements AES CBC mode encryption and decryption

There are five AES encryption methods: ECB, CBC, CTR, CFB, OFB

The CBC encryption method is recommended from the perspective of security. This article introduces the python implementation of CBC and ECB encryption methods.

What to install when using AES    under  Windows is the pycryptodome module pip install pycryptodome 

python  to install when using AES    under Linux is the pycrypto module pip install pycrypto 

CBC encryption requires a sixteen-digit key (key) and a sixteen-digit iv (offset)

1. Encryption

During encryption, the plaintext is first XORed with the IV, and then the result is encrypted in blocks. The output obtained is the ciphertext, and the output ciphertext this time is used as the IV for the next block encryption. 

2. Decryption

When decrypting, first perform block decryption on the first block of ciphertext, and then XOR the result with the IV to obtain the plaintext. At the same time, the input ciphertext decrypted this time is used as the IV for the next block decryption. 



 3. Code:


copy code
# -*- coding=utf-8-*-
from Crypto.Cipher import AES
import os
from Crypto import Random
import base64

aes encryption algorithm
padding : PKCS7

class AESUtil:

    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    def encryt(str, key, iv):
        cipher =, AES.MODE_CBC,iv)
        x = AESUtil.__BLOCK_SIZE_16 - (len(str) % AESUtil.__BLOCK_SIZE_16)
        if x != 0:
            str = str + chr(x)*x
        msg = cipher.encrypt(str)
        # msg = base64.urlsafe_b64encode(msg).replace('=', '')
        msg = base64.b64encode(msg)
        return msg

    def decrypt(enStr, key, iv):
        cipher =, AES.MODE_CBC, iv)
        # enStr += (len(enStr) % 4)*"="
        # decryptByts = base64.urlsafe_b64decode(enStr)
        decryptByts = base64.b64decode(enStr)
        msg = cipher.decrypt(decryptByts)
        paddingLen = ord(msg[len(msg)-1])
        return msg[0:-paddingLen]

if __name__ == "__main__":
    key = "1234567812345678"
    iv = "1234567812345678"
    res = AESUtil.encryt("123456", key, iv)
    print res # 2eDiseYiSX62qk/WS/ZDmg==
    print AESUtil.decrypt(res, key, iv) # 123456
copy code










Related: Python implements AES CBC mode encryption and decryption