#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：cx_aes.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：AES 加解密
"""

import binascii

from Crypto.Cipher import AES


class AESCipher:
    def __init__(self, secret_key: str, iv: str):
        self.BLOCK_SIZE = AES.block_size
        self.pad = lambda s: (
            s
            + (self.BLOCK_SIZE - len(s.encode()) % self.BLOCK_SIZE)
            * chr(self.BLOCK_SIZE - len(s.encode()) % self.BLOCK_SIZE)
        )
        self.unpad = lambda s: s[: -ord(s[len(s) - 1 :])]
        self.key = secret_key
        self.iv = iv

    def encrypt(self, text):
        text = self.pad(text).encode()
        cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
        encrypted_text = cipher.encrypt(text)
        return encrypted_text.hex().upper()

    def decrypt(self, encrypted_text):
        cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
        decrypted_text = cipher.decrypt(binascii.a2b_hex(encrypted_text))
        return self.unpad(decrypted_text).decode("utf-8")


if __name__ == "__main__":
    secret_key = "|dSQG|YRSZ+Q%3*FDo*^G(L]8{D{(4C_"
    # 获取前16位作为IV
    iv = secret_key[:16]
    print("IV:", iv)  # 输出: |dSQG|YRSZ+Q%3*F
    # 获取后16位作为key
    key = secret_key[-16:]
    print("Key:", key)  # 输出: Do*^G(L]8{D{(4C_
    print(AESCipher(secret_key=key, iv=iv).encrypt("test01"))
