aes (English: Advanced encryption Standard, Chinese: Advanced Encryption Standard), is a block encryption standard. AES processes the raw data into several 4x4 byte matrices, and uses a predefined key to encrypt each byte in each byte matrix in an XOR, substitution, shift, and linear transformation operation to achieve the purpose of encryption. The key length can be 128,192 or 256 bits.
Below is an example of using the Python M2crypto Library and encrypting and decrypting using the AES_128_ECB algorithm. First, introduce a few key points:
1, IV (initialization vector), which is the initialization vector, used to avoid multiple encryption of the same data to produce the same ciphertext. The maximum length is 16 bytes, and more than 16 bytes are 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 that each byte matrix can be encrypted at the same time; The disadvantage is that for the relevant data, the ciphertext after encryption is the same.
3, Padding, because AES is processed as a 4x4 byte matrix, because the data to be encrypted must be a multiple of 16, and a fill operation will be performed if the number is less than 16. The AES_128_ECB algorithm encrypts the default fill mode is PKCS5.
From M2CRYPTO.EVP import Cipher to
m2crypto import m2 from
m2crypto import util
encrypt_op = 1 # cryptographic Operations
DE Crypt_op = 0 # decryption operation
IV = ' 16 # initialization variable, useless for AES_128_ECB algorithm
private_key = ' dd7fd4a156d28bade96f816db1d18609 ' # key
def Encrypt (data):
' using the AES_128_ECB algorithm to encrypt '
cipher = cipher (ALG = ' AES_128_ECB ', key = Private_key, IV = IV, OP = encrypt_op)
buf = cipher.update (data)
buf = buf + cipher.final ()
del cipher
# converts plaintext from bytes to 16
Output = ' for
i in buf:
output = + '%02x '% (ord (i)) return
output
def Decrypt (data):
' use Aes_12 8_ECB algorithm for Data decryption '
# Convert ciphertext from 16 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