1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
from Crypto.Cipher import AES import base64
class AESCipher:
def __init__(self, key: str, iv: str): if len(key) != 16 or len(iv) != 16: log.error(f"key or iv 长度异常: {key}, {iv} ") raise ValueError("length error")
self.key = bytes(key, encoding='utf-8') self.iv = bytes(iv, encoding='utf-8')
def pkcs7padding(self, text): """ 明文使用PKCS7填充 最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理 :param text: 待加密内容(明文) :return: """ bs = AES.block_size length = len(text) bytes_length = len(bytes(text, encoding='utf-8')) padding_size = length if (bytes_length == length) else bytes_length padding = bs - padding_size % bs padding_text = chr(padding) * padding return text + padding_text
def pkcs7unpadding(self, text): """ 处理使用PKCS7填充过的数据 :param text: 解密后的字符串 :return: """ try: length = len(text) unpadding = ord(text[length - 1]) return text[0:length - unpadding] except Exception as e: pass
def encrypt(self, content): """ AES加密 key,iv使用同一个 模式cbc 填充pkcs7 :param key: 密钥 :param content: 加密内容 :return: """ cipher = AES.new(self.key, AES.MODE_CBC, self.iv) content_padding = self.pkcs7padding(content) aes_encode_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8')) result = str(base64.b64encode(aes_encode_bytes), encoding='utf-8') return result
def decrypt(self, content): """ AES解密 key,iv使用同一个 模式cbc 去填充pkcs7 :param key: :param content: :return: """ try:
cipher = AES.new(self.key, AES.MODE_CBC, self.iv) aes_encode_bytes = base64.b64decode(content) aes_decode_bytes = cipher.decrypt(aes_encode_bytes) result = str(aes_decode_bytes, encoding='utf-8') result = self.pkcs7unpadding(result) except Exception as e: pass if result == None: return "" else: return result
|