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'') 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')
05-11 22:43