import binascii from Crypto.Cipher import AES #秘鑰,此處需要將字符串轉為字節 from utils import config from utils.env_operation import conf_parse key = b'abcdefgh' #加密內容需要長達16位字符,所以進行空格拼接 class crypt_util(): def __init__(self): self.token = config.get_env('crypt_token').encode('utf-8') self.aes = AES.new(self.token, AES.MODE_CBC,b'0000000000000000') def encrypt(self,text): text = text.encode('utf-8') # 這里密鑰key 長度必須為16(AES-128), # 24(AES-192),或者32 (AES-256)Bytes 長度 # 目前AES-128 足夠目前使用 length = 16 count = len(text) if count < length: add = (length - count) # \0 backspace # text = text + ('\0' * add) text = text + ('\0' * add).encode('utf-8') elif count > length: add = (length - (count % length)) # text = text + ('\0' * add) text = text + ('\0' * add).encode('utf-8') self.ciphertext = self.aes.encrypt(text) # 因為AES加密時候得到的字符串不一定是ascii字符集的,輸出到終端或者保存時候可能存在問題 # 所以這里統一把加密后的字符串轉化為16進制字符串 return binascii.b2a_hex(self.ciphertext) def decrypt(self,str): plain_text = self.aes.decrypt(binascii.a2b_hex(str)) # return plain_text.rstrip('\0') print(bytes.decode(plain_text).rstrip('\0')) return bytes.decode(plain_text).rstrip('\0') # # a = b'8fea87a50aa6203cfcfd508fa30f8fa0d8cd103e3a37ef057f7763eff7742b51' # # 用aes對象進行解密,將字節類型轉為str類型,錯誤編碼忽略不計 # de = self.aes.decrypt(binascii.a2b_hex(str)), encoding='utf-8', errors="ignore") # # 獲取str從0開始到文本內容的字符串長度。 # print(de) # return de def pad(text): while len(text) % 16 != 0: text += b' ' return text #加密秘鑰需要長達16位字符,所以進行空格拼接 def pad_key(key): while len(key) % 16 != 0: key += b' ' return key if __name__ == '__main__': conparse = conf_parse() conparse.confparse(vars) crypt=crypt_util() # print(crypt.encrypt("12345678")) crypt.decrypt('a56586aa860f83d6ba9a826b4c6df564')