AES (Encryption Standard, Chinese: Advanced Encryption Standard), is a block encryption standards. AES is processed by dividing the raw data into multiple 4x4 byte matrices, with a pre-defined key that makes each byte in each byte matrix XOR, replaced, shifted, and linearly transformed to achieve the purpose of encryption. The key length can be 128,192 or 256 bits.
Here is an example of using the Python M2crypto library and using the AES_128_ECB algorithm for encryption and decryption. Let's start by introducing a few key points:
1, iv (initialization vector), that is, the initialization vector, to avoid the same data multiple encryption will produce the same ciphertext. The maximum length is 16 bytes, beyond the 16-byte portion is ignored, preferably randomly generated to increase the strength of the encryption.
2. ECB (Electronic CODEBOOK,ECB), which encrypts each 4x4 byte matrix with the same key and does not use IV. The advantage is that each byte matrix can be encrypted independently, so each byte matrix can be encrypted at the same time, and the disadvantage is that the ciphertext after encryption is the same for the related data.
3, Padding, because AES is a 4x4 byte matrix as a unit for processing, because the data to be encrypted must be a multiple of 16, if less than a multiple of 16, will be filled operation. The AES_128_ECB algorithm encrypts the default fill mode of PKCS5.
From M2CRYPTO.EVP import Cipher to M2crypto import m2 from m2crypto import util Encrypt_op = 1 # encryption Operation Decrypt_op = 0 # decryption Operation IV = ' + ' * 16 # Initialize variable, useless for AES_128_ECB algorithm private_key = ' dd7fd4a156d28bade96f816db1d18609 ' # key def Encrypt (data): ' Use the AES_128_ECB algorithm to encrypt the cipher = cipher (ALG = ' AES_128_ECB ', key = Private_key, IV = IV, OP = encrypt_op)
buf = cipher.update (data) buf = buf + cipher.final () del cipher # Stream clear text from byte to 16 output = ' for i In BUF: output + = '%02x '% (ord (i)) return output def Decrypt (data): ' decryption with the AES_128_ECB algorithm ' # Convert ciphertext from 16 binary to byte stream data = util.h2b (data) cipher = cipher (ALG = ' AES_128_ECB ', key = Private_key, IV = IV, OP = DECR YPT_OP) buf = cipher.update (data) buf = buf + cipher.final () del cipher return BUF