1,crypto的安装:
windows下使用AES时安装pycryptodome 模块,pip install pycryptodome
linux 下使用AES时安装pycrypto模块,pip install pycrypto
2,加密和解密 (AES.ECB(128位) pkcs5padding算法)
```
from Crypto.Cipherimport AES
from binasciiimport b2a_hex, a2b_hex
from Cryptoimport Random
import base64
import json
class AesEncry(object):
# aes秘钥 ,可根据自身需要手动生成
key ="aes_keysaes_keysaes_keys"
def encrypt(self, data):
data = json.dumps(data)
mode = AES.MODE_ECB
padding =lambda s: s + (16 -len(s) %16) *chr(16 -len(s) %16)
cryptos = AES.new(self.key.encode("utf-8"), mode)
cipher_text = cryptos.encrypt(padding(data).encode("utf-8"))
return base64.b64encode(cipher_text).decode("utf-8")
def decrypt(self, data):
cryptos = AES.new(self.key.encode("utf-8"), AES.MODE_ECB)
decrpytBytes = base64.b64decode(data)
meg = cryptos.decrypt(decrpytBytes).decode('utf-8')
return meg[:-ord(meg[-1])]
aes_encry_util = AesEncry()
#明文
data ="mypwd_test"
#加密
encry_data = aes_encry_util.encrypt(data)
print(encry_data)
# 对密文进行解密
decry_data = aes_encry_util.decrypt(encry_data)
print(decry_data)
```
如上便完成了利用python进行AES的ECB加密