@AES-128加密解密方式
from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
from Crypto import Random
import base64
def check_key(key):
# 检测key的长度是否为16,24或者32bytes的长度
try:
if isinstance(key, bytes):
assert len(key) in [16, 24, 32]
return key
elif isinstance(key, str):
assert len(key.encode()) in [16, 24, 32]
return key.encode()
else:
raise Exception(f'密钥必须为str或bytes,不能为{type(key)}')
except AssertionError:
print('输入的长度不正确')
class AesEncryption(object):
# CFB模式
# def __init__(self, key, mode=AES.MODE_CFB):
# self.key = check_key(key)
# # 密钥key长度必须为16,24或者32bytes的长度
# self.mode = mode
# self.iv = Random.new().read(AES.block_size)
# GCM模式
def __init__(self, key, mode=AES.MODE_GCM):
self.key = check_key(key)
# 密钥key长度必须为16,24或者32bytes的长度
self.mode = mode
self.iv = Random.new().read(AES.block_size)
from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
from Crypto import Random
import base64
def check_key(key):
# 检测key的长度是否为16,24或者32bytes的长度
try:
if isinstance(key, bytes):
assert len(key) in [16, 24, 32]
return key
elif isinstance(key, str):
assert len(key.encode()) in [16, 24, 32]
return key.encode()
else:
raise Exception(f'密钥必须为str或bytes,不能为{type(key)}')
except AssertionError:
print('输入的长度不正确')
class AesEncryption(object):
# CFB模式
# def __init__(self, key, mode=AES.MODE_CFB):
# self.key = check_key(key)
# # 密钥key长度必须为16,24或者32bytes的长度
# self.mode = mode
# self.iv = Random.new().read(AES.block_size)
# GCM模式
def __init__(self, key, mode=AES.MODE_GCM):
self.key = check_key(key)
# 密钥key长度必须为16,24或者32bytes的长度
self.mode = mode
self.iv = Random.new().read(AES.block_size)
def check_data(self,data):
# '检测加密的数据类型'
if isinstance(data, str):
data = data.encode()
elif isinstance(data, bytes):
pass
else:
raise Exception(f'加密的数据必须为str或bytes,不能为{type(data)}')
return data
def encrypt(self, data):
# 加密函数
data = self.check_data(data)
cryptor = AES.new(self.key, self.mode,self.iv)
return b2a_hex(cryptor.encrypt(data)).decode()
def decrypt(self,data):
# 解密函数
data = self.check_data(data)
cryptor = AES.new(self.key, self.mode,self.iv)
return cryptor.decrypt(a2b_hex(data)).decode()
if __name__ == '__main__':
key = input('请输入key:')
data = '{"ai":"test-accountId","name":"用户姓名","idNum":"371321199012310912"}'
aes = AesEncryption(key)
# 调用加密函数
e = aes.encrypt(data)
# 调用解密函数
d = aes.decrypt(e)
# 打印加密
print('加密内容: ', e)
# 打印解密
print('解密内容: ', d)
# 返回base64位的加密
en_text = base64.b64encode(bytes(e, 'utf-8'))
# 打听base64加密
print('获得的base64加密: ', en_text)