from Crypto.Cipher import AES
class PrpCrypt(object):
# 密钥(key), 密斯偏移量(iv) CBC模式加密 备注:保证key和iv必须是16位
def __init__(self, key):
self.key = key.encode('utf-8')
self.mode = AES.MODE_CBC
self.iv = '偏移量'.encode('utf-8')
def encrypt(self, text):
text = text.encode('utf-8')
cryptor = AES.new(self.key, self.mode, self.iv)
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 base64.b64encode(self.ciphertext)
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.iv)
plain_text = cryptor.decrypt(base64.b64decode(text))
return plain_text
if __name__ == '__main__':
pc = PrpCrypt('key')
e = pc.encrypt('需要加密的数据')
d = pc.decrypt(e)
print("加密:", str(e,'utf8'))
print("解密:", str(d,'utf8'))
python AES加密使用CBC模式
最新推荐文章于 2024-07-18 17:57:08 发布