资讯中心

python - AES加密解密

📅 2026/7/28 17:43:48
python - AES加密解密
安装依赖库pip install pycryptodomefrom binascii import b2a_base64, a2b_base64 from Crypto.Cipher import AES class AES_CBC(): def __init__(self, key, iv): # key必须为16位字符串 self.key bytes(key, encodingutf-8) self.iv bytes(iv, encodingutf-8) # 加密。text:需要加密的内容 def encrypt(self, text): cryptor AES.new(self.key, AES.MODE_CBC, self.iv) bs 16 length len(text) bytes_length len(bytes(text, encodingutf-8)) # tipsutf-8编码时英文占1个byte而中文占3个byte padding_size length if (bytes_length length) else bytes_length padding bs - padding_size % bs # tipschr(padding)看与其它语言的约定有的会使用\0 padding_text chr(padding) * padding text text padding_text ciphertext cryptor.encrypt(bytes(text, encodingutf-8)) return b2a_base64(ciphertext) # 解密 def decrypt(self, content): cipher AES.new(self.key, AES.MODE_CBC, self.iv) encrypt_bytes a2b_base64(content) decrypt_bytes cipher.decrypt(encrypt_bytes) text str(decrypt_bytes, encodingutf-8) length len(text) unpadding ord(text[length-1]) return text[0:length-unpadding]原文地址