一、AES加密
- 先安装包
- 直接上代码
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
'''
1、cryptor = AES.new(self.key, self.mode, self.key)
self.key:加密密匙值
self.mode:加密模型
self.IV:对称加密补码方式
IV = 16 * '\x00' #对称加密不满足16位的倍数,末尾补空
'''
class aes_encrypt(object):
def __init__(self):
self.key ='dev1234567891011'.encode('utf-8')
self.mode = AES.MODE_CBC
def encrypt(self, text):
text = text.encode('utf-8')
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
length = 16
count = len(text)
if count < length:
add = (length - count)
text = text + ('\0' * add).encode('utf-8')
elif count > length:
add = (length - (count % length))
text = text + ('\0' * add).encode('utf-8')
self.ciphertext = cryptor.encrypt(text)
return b2a_hex(self.ciphertext)
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
plain_text = cryptor.decrypt(a2b_hex(text))
return bytes.decode(plain_text).rstrip('\0')
if __name__ == '__main__':
aes_encrypt = aes_encrypt()
text = '123456789'
encrypt_text = aes_encrypt.encrypt(text)
decrypt_text = aes_encrypt.decrypt(encrypt_text)
print ('原文',text)
print ('加密后',encrypt_text)
print ('解密后',decrypt_text)