AES

AES #

CBC

# -*- coding: UTF-8 -*-

import secrets
import string
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

# python 在 Windows下使用AES时要安装的是pycryptodome 模块   pip install pycryptodome 
# python 在 Linux下使用AES时要安装的是pycrypto模块   pip install pycrypto


# AES CBC模式加解密

# AES key
key = '110511d33fe6470e'.encode()
# cmdb读取的加密数据
encrypted = '1632e64da21bd1596a107f991296245b67c19f573e9da52d87501f83bd6e59dc'


# 填充
def pkcs7_pad(text, block_size):
    pad_number = block_size - len(text) % block_size
    pad_str = chr(pad_number)
    text = text + pad_str * pad_number
    return text


# 去除填充
def pkcs7_unpad(text):
    text = bytes(text)
    pad_len = text[len(text) - 1]
    return text[:len(text) - pad_len]


# 获取随机iv字符串
def get_rand_str(length=16):
    alphabet = string.ascii_letters + string.digits
    rand_str = ''.join(secrets.choice(alphabet) for i in range(length))
    return rand_str


# 加密
def encrypt(raw_data):
    iv = get_rand_str(AES.block_size).encode()
    data = pkcs7_pad(raw_data, AES.block_size)
    crypto = AES.new(key, AES.MODE_CBC, iv)
    encrypted_data = crypto.encrypt(data.encode())
    return b2a_hex(iv + encrypted_data)


# 解密
def decrypt(cipher):
    cipher = a2b_hex(cipher)
    iv = cipher[:AES.block_size]
    crypto = AES.new(key, AES.MODE_CBC, iv)
    plain = crypto.decrypt(cipher[AES.block_size:])
    return pkcs7_unpad(plain)


if __name__ == '__main__':
    test_text = '78934567890432178'
    encrypted_data = encrypt(test_text)
    print("test data:", test_text, len(test_text))
    print(encrypted_data)
    decrypted_data = decrypt(encrypted_data)
    print(decrypted_data, len(decrypted_data))

    raw = decrypt(encrypted)
    print(raw, len(raw))