python 实现AES加解密
AES 只是个基本算法,实现 AES 有几种模式,主要有 ECB、CBC、CFB 和 OFB CTR,直接上代码,此处为AES加密中的CBC模式,EBC模式与CBC模式相比,不需要iv。
import base64
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
class AES3: def __init__(self, key): self.key = key self.mode = AES.MODE_CBC self.iv = self.key def _pad(self, text): key_len = len(self.key) pad = text + (key_len - len(text) % key_len) * chr(key_len - len(text) % key_len) return pad def _unpad(self, text): pad = ord(text[-1:]) return text[0:-pad] # 加密函数 def encrypt(self, text): length = 16 count = len(text) if count % length != 0: add = length - (count % length) else: add = 0 text = text + (‘\0‘ * add) cryptor = AES.new(self.key.encode("utf8"), self.mode, self.iv.encode("utf8")) self.ciphertext = cryptor.encrypt(bytes(text, encoding="utf8")) # AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码 return base64.b64encode(b2a_hex(self.ciphertext)).decode(‘utf-8‘) # 解密函数 def decrypt(self, text): decode = base64.b64decode(text) cryptor = AES.new(self.key.encode("utf8"), self.mode, self.iv.encode("utf8")) plain_text = unpad(cryptor.decrypt(decode)) return a2b_hex(plain_text) .decode(‘utf8‘)
相关推荐
visionzheng 2020-05-04
CloudXli 2020-01-12
LowisLucifer 2020-04-30
dbhllnr 2020-04-26
wordmhg 2020-03-27
wbingyang 2020-02-14
ahnuzfm 2019-12-24
JF0 2019-12-09
hgzhang 2019-10-22
数据与算法之美 2015-03-09
frankwtq 2012-02-02
guohewei 2019-03-28
HerryDong 2018-05-14
zhuyonge 2016-05-19
走在IT的路上 2013-11-07
风吹夏天 2012-08-28
MXstudying 2019-07-01