python3 implements AES encryption, decryption, and error handling

table of Contents

Data 1: Actual measurement is feasible, slightly different

Why should the length of the encrypted text be filled with 16 digits and an error caused by insufficient digits? 

Data 2: Expand Reference


 

Data 1: Actual measurement is feasible, slightly different

 

Preface

I wrote an aes encryption article before, and the writing method was not mature at the time. After referring to the blog of another blogger, I suddenly realized it. Attach the address here:
http://blog.csdn.net/hh775313602/article/details/78991340

coding

#AES-demo

import base64
from Crypto.Cipher import AES

'''
采用AES对称加密算法
'''
# str不是16的倍数那就补足为16的倍数
def add_to_16(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes
#加密方法
def encrypt_oracle():
    # 秘钥
    key = '123456'
    # 待加密文本
    text = 'abc123def456'
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    #先进行aes加密
    encrypt_aes = aes.encrypt(add_to_16(text))
    #用base64转成字符串形式
    encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8')  # 执行加密并转码返回bytes
    print(encrypted_text)
#解密方法
def decrypt_oralce():
    # 秘钥
    key = '123456'
    # 密文
    text = 'qR/TQk4INsWeXdMSbCDDdA=='
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    #优先逆向解密base64成bytes
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    #执行解密密并转码返回str
    decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','') 
    print(decrypted_text)

if __name__ == '__main__':
   # encrypt_oracle()
    decrypt_oralce()

to sum up

The general idea has not changed,

Use the aes of the pyCryptodome module to first set the secret key,

And the text to be encrypted is filled with 16 bits,

Then base64-bit encoding the bytecode generated by aes,

It can be converted into a string form;

 

The decryption idea can be reversed:

First reverse decrypt base64 into bytes, perform decryption encryption and transcode to return str, replace the'\0' of the extra digits with empty

 


[Error 1]: Why should the encrypted text be filled with 16 digits in length and the number of digits is insufficient to cause an error? 

 

[Error message]: Data must be aligned to block boundary in ECB mode                   python When using Crypto for aes ECB mode encryption and decryption, a decryption error is encountered.

[Cause]: The encrypted data is not supplemented, and the data length must be an integer multiple of 16.

[Solution]: Fill in the original data:

# str不是16的倍数那就补足为16的倍数
def add_to_16(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes
python aes加解密 ecb模式 加密 
报错ValueError: Data must be aligned to block boundary in ECB mode


from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
BLOCK_SIZE = 32 # Bytes
 
key = 'abcdefghijklmnop'
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg = cipher.encrypt(pad(b'hello', BLOCK_SIZE))
print(msg.hex())
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg_dec = decipher.decrypt(msg)
print(unpad(msg_dec, BLOCK_SIZE))

需要用block_size 补充位数
此处是模拟php openssl_encrypt($data, "AES-128-ECB", $key, OPENSSL_RAW_DATA)

[Error 2]: [error information]: TypeError: Object type <class'str'> cannot be passed to C code           

     

[Reason]: The data put in the encryptor must be a byte array

[Solution]: base64 transcoding


Data 2: Expand Reference

 

With the rampant and rampant crawlers on the Internet, in order to limit the collection of their own data to the greatest extent, major websites have added various anti-crawling methods, such as:

Generate browser UA fingerprint recognition;
use various verification methods (text messages, sliders, click on Chinese characters, click) to identify;
...
this type of anti-climbing means is a layer of defense, similar to the gates of a castle. As long as you break through this line of defense, you can do whatever you want.

In addition, there are some websites that will carry out a second layer of defense and add various restrictive measures to the data, such as obfuscation and encryption. It's like after we enter the city gate, if we want to enter the inner city of XX, we have to go through the badges and verifications of the officers and soldiers at the gate.

For example, an e-commerce website uses AES encryption in the data, and the returned data is shown in the following figure:

After decryption, we can get the real data as shown in the figure below:

This is achieved using Python for AES decryption. Next, let's introduce the AES encryption and AES decryption of data in Python.

Article Directory

1. Introduction to the AES algorithm The
following content comes from the Internet, you can take a look at it, if you want to learn more, you can find special materials to learn:

The full name of AES is Advanced Encryption Standard, which is an acronym for Advanced Encryption Standard.

The AES encryption standard, also known as the Advanced Encryption Standard Rijndael encryption method, is the 21st century encryption standard that the National Institute of Standards and Technology (NIST) aims to replace DES. The basic requirement of AES is to adopt a symmetric block cipher system. The key length can be 128, 192 or 256 bits, and the block length is 128 bits. The algorithm should be easy to implement on various hardware and software. In 1998, NIST started the first round of AES analysis, testing and solicitation, and a total of 15 candidate algorithms were produced. [1]

The second round of AES2 analysis and testing was completed in March 1999. On October 2, 2000, the US government officially announced the selection of Rijndael, a cryptographic algorithm proposed by Belgian cryptographers Joan Daemen and Vincent Rijmen, as the AES encryption algorithm.

The AES encrypted data block and key length can be any of 128b, 192b, and 256b. AES encryption has many rounds of repetition and transformation. The general steps are as follows: ①Key Expansion; ②InitialRound; ③Repetition rounds (Rounds), each repeated round includes subbytes (SubBytes), row shift (ShiftRows), column Mix (MixColurmns), round key addition operation (AddRoundKey) and other operations; ①Final round (Final Round), there is no column mixing operation (MixColumns) in the final round.

2. AES encryption
Here, we use the CBC mode in the AES encryption algorithm to demonstrate.

As we mentioned above, the CBC mode of the AES encryption algorithm uses keys and offsets to encrypt data, so we first define several public parameters, including original data, keys, offsets and AES CBC Mode, the code is as follows:

a ='''('name':'Mr. State','url':'zmister.com','desc':'Programming application combat')''' # Raw data
k ='zmistercomzmiste'.encode( 'utf-8') # Key
iv = b'1234567890asdfgh' # Offset
mode = AES.MODE_CBC # Mode
plus Python learning qq skirt: 10667510 Free full set of basic learning materials tutorials, programmers learning exchange base camp
is here, we The set key length is a 16-bit string, which is 128-bit bytes. In the AES encryption algorithm, the key length must be a 16-bit string (128 bytes), a 34-bit string (192 bytes), 32-bit string (256 bytes).

Next, we create a function to encrypt the original data:

# Encrypted data
def cryp_str(value):
    value = value.encode('utf-8') # Encode data in utf-8
    cryptor = AES.new(k, mode, iv) # Create a new AES instance
    length = 16
    count = len(value)
    # If the data length is less than the key length
    if count <length:
        add = (length-count)
        # \0 backspace
        text = value + ('\0' * add).encode('utf-8 ')
    elif count> length:
        add = (
        length-( count% length)) text = value + ('\0' * add).encode('utf-8')
    ciphertext = cryptor.encrypt(text) # encrypted character String
    print("Original encrypted data:",ciphertext)
    ciphertext_hex = b2a_hex(ciphertext) # String to hexadecimal data
    print("Hexadecimal encryption:",ciphertext_hex)
    ciphertext_hex_de = ciphertext_hex.decode()
    print("Hexadecimal encrypted string:",ciphertext_hex_de)
    return ciphertext_hex_de
We pass the original data into it and run, and we can get the encrypted data, as shown in the following figure:

After completing the AES encryption of the data using Python, we continue to use Python to decrypt the AES-encrypted data.

3. AES decryption
Compared with AES encryption, AES decryption is much simpler. We first instantiate an AES class, then convert the encrypted hexadecimal data into a string form, then call the decrypt() method of the AES instance to decrypt the data, and finally decode the decrypted data, you can Get the original data, the code is as follows:

# Decrypt data
def decry_str(value):
    cryptor = AES.new(k, mode, iv) # Create an AES instance
    value_hex = a2b_hex(value) # Convert hexadecimal data to a string
    plain_text = cryptor.decrypt(value_hex ) # Decrypt the string
    print("decrypted data:",plain_text)
    print('Decode and decrypt data:',bytes.decode(plain_text).rstrip('\0'))
    return bytes.decode(plain_text).rstrip ('\0')
We pass the previously AES encrypted data into it as a parameter and run it, and finally get the decrypted original data, as shown in the following figure:

In this way, we have completed the AES encryption and decryption of the data using Python.

4. Finally,
in actual websites, it is possible that data is not only encrypted by one encryption method, but more encrypted data will be obfuscated and encrypted using multiple encryption methods. Faced with this situation, you must first find out the encryption process of the data and not try blindly.
 

Guess you like

Origin blog.csdn.net/zzddada/article/details/115208255