from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes
时间: 2025-02-03 11:50:11 浏览: 49
### Python Crypto库 AES加密 解密 示例
为了使用 `Crypto` 库中的 AES 进行加解密操作,首先需要确保已经正确安装了 pycryptodome 库[^2]。
#### 安装依赖库
如果遇到 `ModuleNotFoundError: No module named 'Crypto'` 的错误,则表明尚未安装所需的库。可以通过 pip 来安装:
```bash
pip install pycryptodome
```
#### 密钥与初始化向量(IV)
AES 加密过程中需要用到一个固定长度的密钥以及一个随机生成的 IV (Initialization Vector),这两个参数对于安全性和数据的一致性至关重要。这里采用 16 字节作为密钥和 IV 的大小[^1]。
#### 数据填充(Padding)
由于 AES 是一种分组密码,因此输入的数据长度必须是特定字节数的倍数。当实际待加密的消息不符合这个条件时,就需要对其进行填充处理。PKCS7 填充方式是一种常用的方法,在此示例中将会被应用到消息两端以满足上述需求[^3]。
下面给出完整的 Python 实现代码如下所示:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt_message(key, message):
cipher = AES.new(key, AES.MODE_CBC, get_random_bytes(16))
ct_bytes = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
iv = cipher.iv
return iv + ct_bytes
def decrypt_message(key, ciphertext):
iv = ciphertext[:16]
ct = ciphertext[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8')
return pt
key = b'Sixteen byte key'
message = "This is a secret message."
ciphertext = encrypt_message(key, message)
print(f"Cipher Text: {ciphertext.hex()}")
plaintext = decrypt_message(key, ciphertext)
print(f"Plain Text : {plaintext}")
```
这段程序展示了如何利用 `pycryptodome` 提供的功能完成一次简单的 AES CBC 模式的加密过程,并能够成功恢复原始明文信息。
阅读全文
相关推荐



















