import hashlib
from Crypto.Cipher import AES


class PasswordEncrypt(object):
    """通过对密码进行加密，方便spd系统登录之后获取token
      spd项目token不存于数据库中，token只存在于内存中
    """

    def __init__(self, username, userpwd, verifyCodeId):
        self.username = username  # 用户名
        self.userpwd = userpwd  # 密码
        self.verifyCodeId = verifyCodeId  # 验证码id

    # 此函数实现密码加密
    def pwd_Encrypt(self):
        '''
        {"username":"gyqxadmin",
         "passwd":"af5d87060df01ce434e4a397b51a0b9bd960416aa873177889f6a0104b28e450acc980ab8d6391931a8470a91c37c94fad5d14f4925d860fb3314aca9bc4677a3ade29e23fb469b8710680995f8e218f",
         "verifyCodeId":"512cdfebc1a042fa89d0f5a56d744f4d","verifyCode":"ece6","projectCode":"warehouse.pc"}
        '''

        # verifyCodeId = b'512cdfebc1a042fa89d0f5a56d744f4d'
        verifyCodeId = self.verifyCodeId
        verifyCode = bytes(verifyCodeId[0:16])
        # print("verifyCode:", verifyCode)
        username_and_pwd = self.username + self.userpwd
        sha256EncodeStr = hashlib.sha256(username_and_pwd.encode("utf-8"))
        # print("sha256EncodeStr:", sha256EncodeStr.hexdigest())
        # print("encode sha256EncodeStr:", sha256EncodeStr.hexdigest().encode("utf-8"))

        aes = AES.new(key=bytes(verifyCodeId), iv=verifyCode, mode=AES.MODE_CBC)
        en_text = aes.encrypt(self.pad(sha256EncodeStr.hexdigest()).encode("utf-8"))  # 加密明文

        # print("en_text:", en_text)
        # print("base64 de_text2:", en_text.hex())
        # print('en_text',en_text)
        return en_text.hex()

    def pad(slef, text):
        # print(type(text))
        text_length = len(text)
        amount_to_pad = AES.block_size - (text_length % AES.block_size)
        # print('amount_to_pad',amount_to_pad)
        # print(type(amount_to_pad))
        if amount_to_pad == 0:
            amount_to_pad = AES.block_size
        pad = chr(amount_to_pad)
        # print('pad',pad)
        # print(text+pad * amount_to_pad)
        return text + pad * amount_to_pad


if __name__ == '__main__':
    aa = PasswordEncrypt('1679886114521', 'a123456!', b'9baf0389a84047fa8e8db78bd8c3530a')
    print(aa.pwd_Encrypt())
