Python AES encryption and decryption, and pythonaes encryption and decryption

Source: Internet
Author: User
Tags rounds

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.