用python实现AES-ECB加密解密
import base64
import hashlib
import json
from Crypto.Cipher import AES
secret = '1111111111111111'
BLOCK_SIZE = 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:])]
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]
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)
text2 = add_to_16(text1)
key2 = get_sha1prng_key(secret)
cryptos = AES.new(bytes.fromhex(key2), mode)
cipher_text = cryptos.encrypt(text2)
encrypted_text = str(base64.encodebytes(cipher_text), encoding='utf-8')
return encrypted_text
def decrypt(text):
mode = AES.MODE_ECB
key2 = get_sha1prng_key(secret)
cryptor = AES.new(bytes.fromhex(key2), mode)
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
decrypted_text = str(cryptor.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
decrypted_text1 = unpad(decrypted_text)
return decrypted_text1
req_data = {
"name": "李四"
}
content = encrypt(str(req_data))
decrypt_data = decrypt(content)
print("明文:", decrypt_data)
print("Key:", secret)
print("密文:", content)
明文: {'name': '李四'}
Key: 1111111111111111
密文: yjGG1V9JYO4/ezGJw8yY3lm390MgKwDjHV1jxZUz+/8=