Python uses the M2Crypto module for AES Encryption
AES (Advanced Encryption Standard, Chinese: Advanced Encryption Standard) is a block Encryption Standard. AES divides the raw data into multiple 4*4-byte matrices for processing, encryption is achieved by performing exclusive or replacement, shift, and linear transformation operations on each byte in each byte matrix using a predefined key. The key length can be 128,192 or 256 bits.
The following is an example of using the Python M2Crypto Library and the aes_128_ecb Algorithm for encryption and decryption. First, we will introduce several key points:
1. iv (Initialization vector), that is, the Initialization vector, is used to avoid the same ciphertext generated when the same data is encrypted multiple times. The maximum length is 16 bytes, and the part exceeding 16 bytes will be ignored. It is best to generate it randomly to increase the encryption strength.
2. ECB (Electronic codebook, ECB) encrypts each 4 × 4-byte matrix with the same key, and IV is not used. The advantage is that each byte matrix can be encrypted independently, so each byte matrix can be encrypted at the same time. The disadvantage is that the encrypted ciphertext is the same for the relevant data.
3. Padding. Because AES processes data in a 4 × 4-byte matrix, the data to be encrypted must be a multiple of 16. If the number is less than 16, the data will be filled. The default filling mode of aes_128_ecb algorithm encryption is pkcs5.
From M2Crypto. EVP import Cipherfrom M2Crypto import m2from M2Crypto import utilENCRYPT_OP = 1 # encryption operation DECRYPT_OP = 0 # decryption operation iv = ''* 16 # initialization variable, private ate_key = 'authorization' # key def Encrypt (data): 'encrypt data using the aes_128_ecb algorithm 'cipher = cipher (alg = 'aes _ 128_ecb ', key = PRIVATE_KEY, iv = iv, op = ENCRYPT_OP) buf = cipher. update (data) buf = buf + cipher. final () del cipher # convert plaintext from byte to hexadecimal output = ''for I in buf: output + = '% 02x' % (ord (I )) return outputdef Decrypt (data): 'decrypt data using the aes_128_ecb algorithm '# convert the ciphertext from hexadecimal format 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