aes加密算法Python实现
时间: 2024-12-22 16:26:44 浏览: 32
AES(Advanced Encryption Standard)是一种对称密钥加密算法,它被广泛应用于数据保护领域。在Python中,我们可以使用`cryptography`库来实现AES加密。以下是一个简单的例子,展示了如何创建一个AES加密器和解密器:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def generate_key(key_size=16):
return bytes.fromhex('0123456789abcdef'[i*2:i*2+2] for i in range(key_size // 2))
def pad_data(data, block_size=16):
padding = block_size - len(data) % block_size
return data + bytes([padding]) * padding
def encrypt(plaintext, key):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend)
encryptor = cipher.encryptor()
padded_plaintext = pad_data(plaintext)
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
return ciphertext
def decrypt(ciphertext, key):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend)
decryptor = cipher.decryptor()
padded_ciphertext = decryptor.update(ciphertext) + decryptor.finalize()
unpadded_plaintext = padded_ciphertext[:len(padded_ciphertext) - padded_ciphertext[-1]]
return unpadded_plaintext.decode()
# 使用示例
key = generate_key()
plaintext = "This is a secret message"
ciphertext = encrypt(plaintext.encode(), key)
print(f"Ciphertext: {ciphertext.hex()}")
decrypted_text = decrypt(ciphertext, key)
print(f"Decrypted Text: {decrypted_text}")
阅读全文