Python AES Encryption decryption

Source: Internet
Author: User
Tags decrypt rounds

AES encrypted block packet length must be 128 bits, the key length can be 128 bits, 192 bits, 256 bits of any one (if the data block and key length is insufficient, will be filled). AES encryption has many rounds of repetition and transformation. The approximate steps are as follows: 1, key expansion (keyexpansion), 2, initial wheel (Initial Round), 3, repeating wheel (Rounds), each round also includes: Subbytes, Shiftrows, Mixcolumns, AddRoundKey , 4, the final round (final Round), the final wheel is not mixcolumns.

AES's encryption and decryption methods are as follows, where password can only be 16,24 or 32-bit strings.

# encoding:utf-8from Crypto.cipher Import aesfrom Crypto import randomdef Encrypt (data, password):    bs = Aes.block_siz e    pad = lambda s:s + (bs-len (s)% BS) * CHR (Bs-len (s)% bs)    IV = Random.new (). Read (BS)    cipher = Aes.new (P Assword, 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__ ':d ata = ' Hello world ' password = ' 1111111111111111 ' #16, 24, 32-bit long password Encrypt_data = Encrypt (data, password) print ' Encrypt_data: ', Encrypt_datadecrypt_data = Decrypt (encrypt_data, password) print ' Decrypt_data: ', Decrypt_data

If you are prompted without crypto to cause execution to fail, you can use PIP install Pycrypto to install the appropriate module to resolve the issue.

The results of the implementation are as follows:




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Python AES Encryption decryption

Related Article

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.