用python实现AES-ECB加密解密
程序员文章站
2022-04-09 16:52:14
...
用python实现AES-ECB加密解密
# AES-ECB加密
import base64
import hashlib
import json
from Crypto.Cipher import AES
# 秘钥
secret = '1111111111111111'
BLOCK_SIZE = 16 # Bytes
# 补位,补齐16位
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
# 去除补位
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
# 使用SHA1方法生成的随机数,对key做处理
def get_sha1prng_key(key):
signature = hashlib.sha1(key.encode()).digest()
signature = hashlib.sha1(signature).digest()
return ''.join(['%02x' % i for i in signature]).upper()[:32]
# 判断data是否为16的整数倍,不足的补"\0"
def add_to_16(text):
if len(text.encode('utf-8')) % 16:
add = 16 - (len(text.encode('utf-8')) % 16)
else:
add = 0
text = text + ('\0' * add)
return text.encode('utf-8')
# 加密函数
def encrypt(text):
mode = AES.MODE_ECB
# 补位
text1 = pad(text)
# 不足16位补上"\0"
text2 = add_to_16(text1)
key2 = get_sha1prng_key(secret)
cryptos = AES.new(bytes.fromhex(key2), mode)
cipher_text = cryptos.encrypt(text2)
# 用base64转成字符串形式
encrypted_text = str(base64.encodebytes(cipher_text), encoding='utf-8') # 执行加密并转码返回bytes
return encrypted_text
# 解密,要先去掉补足的空格用strip()去掉
def decrypt(text):
mode = AES.MODE_ECB
key2 = get_sha1prng_key(secret)
cryptor = AES.new(bytes.fromhex(key2), mode)
# 优先逆向解密base64成bytes
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
# 执行解密密并转码返回str
decrypted_text = str(cryptor.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
# 去除补位
decrypted_text1 = unpad(decrypted_text)
return decrypted_text1
req_data = {
"name": "李四"
}
# dict格式的可以用json.dumps序列化
# req_data = json.dumps(req_data)
content = encrypt(str(req_data))
decrypt_data = decrypt(content)
print("明文:", decrypt_data)
print("Key:", secret)
print("content:", content)
#结果
明文: {'name': '李四'}
Key: 1111111111111111
密文: yjGG1V9JYO4/ezGJw8yY3lm390MgKwDjHV1jxZUz+/8=