aes加密算法python实现
时间: 2023-09-29 09:03:07 浏览: 24
你可以使用 `pycryptodome` 库来实现 AES 加密算法。以下是一个简单的示例:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 16字节的密钥
key = get_random_bytes(16)
# 16字节的初始化向量
iv = get_random_bytes(16)
# 加密函数
def encrypt(plaintext):
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(plaintext)
return ciphertext
# 解密函数
def decrypt(ciphertext):
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
return plaintext
# 测试
plaintext = b"Hello World!"
ciphertext = encrypt(plaintext)
print("加密后的密文:", ciphertext)
decrypted_plaintext = decrypt(ciphertext)
print("解密后的明文:", decrypted_plaintext)
```
注意,这个示例中使用了 CBC 模式和随机生成的密钥和初始化向量。在实际应用中,你需要选择适当的模式和密钥管理方案。另外,如果你需要对字符串进行加密,需要先将字符串转换为字节串(即 `str.encode()`)。