# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64


class Aes:
    def __init__(self):
        self.mode = AES.MODE_CBC

    def pkcs7padding(self, text):
        bs = 16
        length = len(text)
        bytes_length = len(text.encode('utf-8'))
        padding_size = length if (bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        padding_text = chr(padding) * padding
        self.coding = chr(padding)
        return text + padding_text

    def encode(self, content, key, iv):
        result = ""
        try:
            cipher = AES.new(key.encode("utf-8"),
                             AES.MODE_CBC,
                             iv.encode("utf-8"))
            content_padding = self.pkcs7padding(content)
            encrypt_bytes = cipher.encrypt(content_padding.encode('utf-8'))
            result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
        except Exception:
            print("加密失败")
        finally:
            return result

    def decode(self, content, key, iv):
        result = ""
        try:
            cipher = AES.new(key.encode("utf-8"),
                             AES.MODE_CBC,
                             iv.encode("utf-8"))
            content = base64.b64decode(content)
            text = cipher.decrypt(content).decode('utf-8')
            result = text.rstrip().rstrip("\x01").\
                rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").\
                rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").\
                rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").\
                rstrip("\x0e").rstrip("\x0f").rstrip("\x10")
        except Exception:
            print("解密失败")
        finally:
            return result
