python實現AES對稱加解密
關於aes對稱加密的概念網上很多,在此不在贅述,直接上代碼。
import base64
from Crypto.Cipher import AES
"""
AES加密解密工具類
數據塊128位
key 爲16位
iv 爲16位
AES加密模式爲cbc
填充 pkcs7padding
"""
class MyRes(object):
def __init__(self, key):
self.key = key
@staticmethod
def pkcs7padding(text):
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
# chr(padding)看與其它語言的約定,有的會使用'\0'
padding_text = chr(padding) * padding
return text + padding_text
@staticmethod
def pkcs7unpadding(text):
length = len(text)
unpadding = ord(text[length-1])
return text[0:length-unpadding]
def encrypt(self, content):
key_bytes = bytes(self.key, encoding='utf-8')
iv = key_bytes
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
content_padding = self.pkcs7padding(content)
encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
return result
def decrypt(self, content):
key_bytes = bytes(self.key, encoding='utf-8')
iv = key_bytes
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
encrypt_bytes = base64.b64decode(content)
decrypt_bytes = cipher.decrypt(encrypt_bytes)
result = str(decrypt_bytes, encoding='utf-8')
result = self.pkcs7unpadding(result)
return result
if __name__ == '__main__':
text = "hello world"
myrsa = MyRes("1234567890abcdef")
encrypt_text = myrsa.encrypt(text)
print("加密後:", encrypt_text)
decrypt_text = myrsa.decrypt(encrypt_text)
print("解密後:", decrypt_text)