ascii(hex)/aes_ecb

来源:互联网 发布:知源中学复读 编辑:程序博客网 时间:2024/06/07 23:16

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

import binasciifrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modesfrom 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_textdef 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_textif __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))