Python implements AES_256 CBC mode encryption algorithm

AES

AES (Advanced Encryption Standard) Advanced Encryption Standard. It is a block encryption standard adopted by the US federal government. This standard is used to replace the original DES, which has been analyzed by many parties and is widely used all over the world. After a multi-year selection process, the Advanced Encryption Standard was published by the National Institute of Standards and Technology (NIST) in FIPS PUB 197 on November 26, 2001, and became a valid standard on May 26, 2002. In 2006, the Advanced Encryption Standard had become one of the most popular algorithms in symmetric key encryption.

There are three most common AES schemes, namely AES-128, AES-192 and AES-256. The difference between them is that the key length is different. The key length of AES-128 is 16bytes (128bit / 8). The latter two 24bytes and 32bytes respectively.
The longer the key, the higher the security strength, but with the increase of the number of operation rounds, the operation overhead will be larger, so the user should make a reasonable choice according to different applications.
In the application process, users should not only pay attention to the key length, but also pay attention to the confirmation algorithm mode. The AES algorithm has five encryption modes, namely CBC, ECB, CTR, OCF, and CFB. The latter three modes are more complicated and less used, so the CBC encryption method is recommended from the perspective of security.
The full name of ECB mode is Electronic Codebook Book, which is the code book mode. In this mode, the entire plaintext is divided into several groups of the same length, then each group is encrypted, and the encrypted result is spliced ​​into the final result, C = C1C2C3...Cn. It is basically the same as the encryption process of the DES algorithm in ECB mode.
The full name of CBC mode is Cipher Block Chaining. In this mode, the plaintext is first divided into several groups of the same length (same as ECB mode). At this time, the initial vector IV is used to XOR the first group of data before encryption. The operation generates C1. Take C1 as the initial vector and perform XOR with the second set of data, and then perform encryption operation to generate C2. By analogy, when the last set of data is encrypted, the encrypted result is spliced ​​into the final result, C = C1C2C3...Cn.

Python implements AES

First of all, you must install the module to prevent everyone from stepping on the pit. You must distinguish the development environment. The installation packages of different environments are different. Otherwise, an installation error will appear, indicating that you are missingmicrosoft visual c++ 2015. Avoid the dilemma of encountering but not being able to install it. If you have already installed but still cannot load the module, try uninstalling and reinstalling.
python to install when using AES under Windows ispycryptodomemodule,pip install pycryptodome
python to install when using AES under Linux ispycryptomodule,pip install pycrypto
CBC encryption requires a sixteen-digit key (key) and a sixteen-digit iv (offset)

encryption

During encryption, the plaintext is first XORed with the IV, and then the result is encrypted in blocks. The output obtained is the ciphertext, and the output ciphertext this time is used as the IV for the next block encryption.
insert image description here

decrypt

When decrypting, first perform block decryption on the first block of ciphertext, and then XOR the result with the IV to obtain the plaintext. At the same time, the input ciphertext decrypted this time is used as the IV for the next block decryption.
insert image description here

Code

from Crypto.Cipher import AES
import os
from Crypto import Random
import base64

"""
aes encryption algorithm
padding : PKCS7
"""

class  AESUtil :

    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    @staticmethod
    def encryt(string, key, iv):
        """
        encrypted text
        :param string: text
        :param key: key
        :param iv: offset/initial vector
        :return: ciphertext
        """ 
        cipher = AES . new ( key , AES . MODE_CBC , iv ) 
        x = AESUtil . __BLOCK_SIZE_16 -  ( len ( string )  % AESUtil . __BLOCK_SIZE_16 ) 
        # If the last block is less than 16 bits, it needs to be filled with characters 
        if x !=  0 : 
            string = string +  chr ( x ) * x
        msg = cipher.encrypt(string.encode('utf-8'))
        
        # msg = base64.urlsafe_b64encode(msg).replace('=', '')
        # msg = base64.b64encode(msg)
        return msg

    @staticmethod
    def decrypt(en_str, key, iv):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        # en_str += (len(en_str) % 4)*"="
        # decryptByts = base64.urlsafe_b64decode(en_str)
        # decryptByts = base64.b64decode(en_str)
        # msg = cipher.decrypt(decryptByts)

        msg = cipher.decrypt(en_str)
        padding_len = msg[len(msg)-1]
        return msg[0:-padding_len]


if __name__ ==  "__main__" : 
    # import hashlib 
    # key = hashlib.md5().hexdigest() # Randomly generate a md5 value, 32-bit 
    string =  '{"key": "123456"}' 
    key = b "d41d8cd98f00b204e9800998ecf8427e "    # 32-bit 
    iv = b "1234567812345678"     # 16-bit 
    res = AESUtil . encryt ( string , key , iv ) 
    print ( res )   # \xbf\xd7\xf7\xfc\x1c\x15\x93\xc1*Z\xc3 \x0e\xda\x85\xdb\x9d\x9a\xb6z\xbb\xa7\xb3&\x8b\xa1\xd3\xc6\xf13;\xf3\n
    print(AESUtil.decrypt(res, key, iv))    # {"key": "123456"}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

Reference link: http://www.ifindbug.com/doc/id-44800/name-Python implements AES CBC mode encryption and decryption.html

Related: Python implements AES_256 CBC mode encryption algorithm