ascii(hex)/aes_ecb

针对密钥和密文明文都是ascii(hex)形式进行aes_ecb加密和解密



import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7

# 将密钥的ascii(hex)形式转换成字符串
key = binascii.unhexlify('68656c6c6f776f726c6468656c6c6f31')
print('key: {}'.format(key))


def aes_ecb_encrypt(text):
    encryptor = Cipher(
        algorithms.AES(key),
        modes.ECB(),
        backend=default_backend(),
    ).encryptor()

    padder = PKCS7(128).padder()
    cipher_text = encryptor.update(padder.update(text) + padder.finalize())
    return cipher_text


def aes_ecb_decrypt(text):
    decryptor = Cipher(
        algorithms.AES(key),
        modes.ECB(),
        backend=default_backend()
    ).decryptor()
    de_text = decryptor.update(binascii.unhexlify(text))
    de_text = str(de_text).replace(r'\x05', '')
    return de_text


if __name__ == '__main__':
    # 加密
    cipher_text = aes_ecb_encrypt(b'12345678910')
    print('cipher_text: {}'.format(cipher_text))
    # 将密文转成ascii(hex)
    hex_text = binascii.hexlify(cipher_text)
    print('hex_text: {}'.format(hex_text))
    # 将密文的ascii(hex)形式转成明文
    plaintext = aes_ecb_decrypt(hex_text)
    print('plaintext: {}'.format(plaintext))

猜你喜欢

转载自blog.csdn.net/shuishou07/article/details/78625042
今日推荐