AES加密解密:
python3.6首先需安装pycryptodome模块
不使用函数:
from Crypto.Cipher import AES
import base64
def add_to_16(s):
while len(s)%16 != 0:
s += '\0'
return str.encode(s)
key = '1234567890123456'# 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
text = 'hello,world'
aes = AES.new(str.encode(key),AES.MODE_ECB)# 初始化加密器,本例采用ECB加密模式
encrypt = str(base64.encodebytes(aes.encrypt(add_to_16(text))),encoding='utf-8').replace('\n','')#加密
decrypt = str(aes.decrypt(base64.decodebytes(bytes(encrypt,encoding='utf-8'))).rstrip(b'\0').decode('utf8'))#解密
print(encrypt)
print(decrypt)
运行结果:
使用函数:
from Crypto.Cipher import AES
import base64
class testAES:
def __init__(self,key):
self.key = key
self.aes = AES.new(str.encode(key), AES.MODE_ECB)
def add_to_16(self,s):
while len(s) % 16 != 0:
s += '\0'
return str.encode(s)
#加密方法
def Encrypt(self,text):
encryption = str(base64.encodebytes(self.aes.encrypt(self.add_to_16(text))), encoding='utf-8').replace('\n', '')
return encryption
#解密方法
def Decrypt(self,text):
decryption = str(self.aes.decrypt(base64.decodebytes(bytes(text,encoding='utf-8'))).rstrip(b'\0').decode('utf8'))
return decryption
if __name__ == '__main__':
key = '1234567890123456'#初始化秘钥为16位
passwd = 'hello,python'
encrypt_text = testAES(key).Encrypt(passwd)
decrypt_text = testAES(key).Decrypt(encrypt_text)
print(encrypt_text)
print(decrypt_text)
运行结果: