# Tutorial on AES encryption using the M2Crypto module in Python

- 2020-05-07 19:57:12
- OfStack

AES(Advanced Encryption Standard) is a block encryption standard. AES divides the raw data into multiple 4 by 4 byte matrices for processing, and performs xor, replace, shift, and linear transformation operations on each byte in each byte matrix with a predefined key to achieve the purpose of encryption. The key length can be 128,192 or 256 bits.

The following is an example of using the Python M2Crypto library for encryption and decryption using the aes_128_ecb algorithm. Firstly, the following key points are introduced:

1. iv(Initialization vector), namely the initialization vector, is used to prevent the same data from being encrypted for many times to produce the same ciphertext. The maximum length is 16 bytes, beyond which portions are ignored and are best generated at random to increase the strength of the encryption.

2. ECB (Electronic codebook, ECB), which encrypts each 4 by 4 byte matrix with the same key and USES IV. The advantage is that each byte matrix can be encrypted independently, so each byte matrix can be encrypted simultaneously. The disadvantage is that for the relevant data, the ciphertext after encryption is 1.

3. Padding, because AES is processed in a unit of 4×4 byte matrix, because the data to be encrypted must be a multiple of 16, if it is less than a multiple of 16, it will be filled. aes_128_ecb algorithm encryption the default fill mode is pkcs5.

```
from M2Crypto.EVP import Cipher
from M2Crypto import m2
from M2Crypto import util
ENCRYPT_OP = 1 # Cryptographic operations
DECRYPT_OP = 0 # Decryption operation
iv = '\0' * 16 # Initialize the variable, for aes_128_ecb Algorithm is useless
PRIVATE_KEY = 'dd7fd4a156d28bade96f816db1d18609' # The key
def Encrypt(data):
' use aes_128_ecb The algorithm encrypts the data '
cipher = Cipher(alg = 'aes_128_ecb', key = PRIVATE_KEY, iv = iv, op = ENCRYPT_OP)
buf = cipher.update(data)
buf = buf + cipher.final()
del cipher
# Flows the plaintext from byte to 16 Into the system
output = ''
for i in buf:
output += '%02X' % (ord(i))
return output
def Decrypt(data):
' use aes_128_ecb The algorithm decrypts the data '
# The cipher text from 16 Convert base to byte stream
data = util.h2b(data)
cipher = Cipher(alg = 'aes_128_ecb', key = PRIVATE_KEY, iv = iv, op = DECRYPT_OP)
buf = cipher.update(data)
buf = buf + cipher.final()
del cipher
return buf
```