天天看點

aes加密算法python語言實作_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, encoding='utf-8')

self.iv = bytes(iv, encoding='utf-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, encoding='utf-8'))

# tips:utf-8編碼時,英文占1個byte,而中文占3個byte

padding_size = length if (bytes_length == length) else bytes_length

padding = bs - padding_size % bs

# tips:chr(padding)看與其它語言的約定,有的會使用'\0'

padding_text = chr(padding) * padding

text = text + padding_text

ciphertext = cryptor.encrypt(bytes(text, encoding='utf-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, encoding='utf-8')

length = len(text)

unpadding = ord(text[length-1])

return text[0:length-unpadding]