Python中AES的加密和解密

可以使用Python中的cryptography库进行AES加密。

1、首先需要安装cryptography库,可以使用以下命令进行安装:

pip install cryptography 2、接下来可以按照以下步骤进行AES加密:

导入所需的模块。 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend 准备密钥和明文。 key = b'Sixteen byte key' # 16字节的密钥 plaintext = b'Test plaintext' 选择加密模式和填充方式。 backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) encryptor = cipher.encryptor() padder = padding.PKCS7(algorithms.AES.block_size).padder() 进行加密操作。 padded_data = padder.update(plaintext) + padder.finalize() ciphertext = encryptor.update(padded_data) + encryptor.finalize()

print(ciphertext)

完整代码示例:

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

准备密钥和明文 key = b'Sixteen byte key' # 16字节的密钥 plaintext = b'Test plaintext'

选择加密模式和填充方式 backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) encryptor = cipher.encryptor() padder = padding.PKCS7(algorithms.AES.block_size).padder()

进行加密操作 padded_data = padder.update(plaintext) + padder.finalize() ciphertext = encryptor.update(padded_data) + encryptor.finalize()

print(ciphertext)

使用cryptography库进行AES解密也很简单,可以按照以下步骤:

导入所需的模块。 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend 准备密钥和密文。 key = b'Sixteen byte key' # 16字节的密钥 ciphertext = b'\xcf\xb2\x04|\xb9\x90\xd4\xb01\xb4\xf4\xad\xce\r\xf4\x16' 选择加密模式和填充方式。 backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) decryptor = cipher.decryptor() 进行解密操作。 plaintext_padded = decryptor.update(ciphertext) + decryptor.finalize() unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() plaintext = unpadder.update(plaintext_padded) + unpadder.finalize()

print(plaintext)

完整代码示例:

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

准备密钥和密文 key = b'Sixteen byte key' # 16字节的密钥 ciphertext = b'\xcf\xb2\x04|\xb9\x90\xd4\xb01\xb4\xf4\xad\xce\r\xf4\x16'

选择加密模式和填充方式 backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) decryptor = cipher.decryptor()

进行解密操作 plaintext_padded = decryptor.update(ciphertext) + decryptor.finalize() unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() plaintext = unpadder.update(plaintext_padded) + unpadder.finalize()

print(plaintext)

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0