Python AES encryption and decryption, and pythonaes encryption and decryption
The length of the AES encrypted data block group must be 128 bits, and the key length can be any of the 128 bits, 192 bits, and 256 bits (if the length of the data block and the key is insufficient, it will be completed ). AES encryption involves many rounds of repetition and transformation. The general steps are as follows: 1. KeyExpansion, 2. Initial Round, 3. repeated Rounds. Each Round includes: subBytes, ShiftRows, MixColumns, AddRoundKey, 4. Final Round. The Final Round does not contain MixColumns.
The encryption and decryption methods of AES are as follows. The password can only be a string of 16, 24, or 32 characters.
# Encoding: utf-8from Crypto. cipher import AESfrom Crypto import Randomdef encrypt (data, password): bs = AES. block_size pad = lambda s: s + (bs-len (s) % bs) * chr (bs-len (s) % bs) iv = Random. new (). read (bs) cipher = AES. new (password, AES. MODE_CBC, iv) data = cipher. encrypt (pad (data) data = iv + data return datadef decrypt (data, password): bs = AES. block_size if len (data) <= bs: return data unpad = lambda s: s [0:-ord (s [-1])] iv = data [: bs] cipher = AES. new (password, AES. MODE_CBC, iv) data = unpad (cipher. decrypt (data [bs:]) return data if _ name _ = '_ main __': data = 'Hello world' password = '000000' #16, 24, 32-bit long password encrypt_data = encrypt (data, password) print 'encrypt _ data :', encrypt_datadecrypt_data = decrypt (encrypt_data, password) print 'crypt _ data: ', decrypt_data
If the execution fails because no Crypto is prompted, you can use pip install pycrypto to install the corresponding module to solve the problem.
The execution result is as follows:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.