介绍
AES是一种对称加密,使用同一个密钥来加密和解密一段密文
安装
pip install pycryptodome
基础语法
aes = AES.new(key,AES.MODE,iv)
#加密
aes.encrypt(content)
#解密
aes.decrypt(content)
key
自定义的密匙
AES.MODE(用于加密或解密的链接模式)
-
ECB:是一种基础的加密方式,密文被分割成分组长度相等的块(不足补齐),然后单独一个个加密,一个个输出组成密 文。
-
CBC:是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度。
-
CFB/OFB实际上是一种反馈模式,目的也是增强破解的难度。
iv
用于加密或解密的初始化向量
实例
from Crypto.Cipher import AES
from Crypto import Random
class AEScoding(object):
def __init__(self,data):
self.data = data
self.key = b'this is a 16 key' #生成密钥
self.iv = Random.new().read(AES.block_size)
self.ciphertext=""
def encrypt(self):
cipher = AES.new(self.key,AES.MODE_CFB,self.iv) #生成AES对象
ciphertext= cipher.encrypt(self.data.encode())
self.ciphertext = ciphertext
return ciphertext
def decrypt(self):
decrypt = AES.new(self.key, AES.MODE_CFB, self.iv)
decrypttext = decrypt.decrypt(self.ciphertext)
return decrypttext.decode()
if __name__=='__main__':
data = 'this is a key'
aes = AEScoding(data)
encode = aes.encrypt()
print(encode)
decode = aes.decrypt()
print(decode)